Creating a Wordscramble using matlab

Hi, working on a review sheet (not for a grade), and I need to create a function that recieves a word and scrambles every letter except for the first and last letters of the word. I've already created a function that scrambles a word entirely in a previous problem, but I can't figure out how to rearrange it to leave the first and last letters unscrambled. Here's my function:
function outword =wordscramble(inword)
len = length(inword);
% Puts random index in the first element
indvec = zeros(1,len);
indvec(1) = randi([1 len]);
% Makes sure every index is only used one time
for i = 2:len
ran = randi([1 len]);
while any(indvec(1:i-1)== ran)
ran = randi([1,len]);
end
indvec(i) = ran;
end
outword = inword(indvec);
end

 採用された回答

Ameer Hamza
Ameer Hamza 2020 年 4 月 21 日
編集済み: Ameer Hamza 2020 年 4 月 21 日

0 投票

Try this
function outword = wordscramble(inword)
outword = inword;
n = numel(inword);
idx = randperm(n-2)+1;
outword(2:end-1) = outword(idx);
end
Example
>> wordscramble('A quick brown fox')
ans =
'Acqoouwb f r iknx'

5 件のコメント

AJ Schmidt
AJ Schmidt 2020 年 4 月 21 日
Although your function yields the correct answer, my instructor hasn't taught us the randperm function yet, so I wouldn't be able to use that function on a test or homework assignment. Thanks for finding an answer!
Ameer Hamza
Ameer Hamza 2020 年 4 月 21 日
Try this version free of randperm:
function outword = wordscramble(inword)
outword = inword;
n = numel(inword);
vec = 2:n-1;
idx = zeros(size(vec));
for i=1:numel(vec)
I = randi([1 numel(vec)], 1);
idx(i) = vec(I);
vec(I) = [];
end
outword(2:end-1) = outword(idx);
end
Test:
>> wordscramble('A quick brown fox')
ans =
'Ao oi bfcnurkwqx'
AJ Schmidt
AJ Schmidt 2020 年 4 月 21 日
That should do the trick, thanks for your help!
Ameer Hamza
Ameer Hamza 2020 年 4 月 21 日
I am glad to be of help.
Stephen23
Stephen23 2020 年 4 月 21 日
You can create your own randperm by sorting any random vector of numbers:
>> str = 'A quick brown fox';
>> [~,idx] = sort(rand(1,numel(str)));
>> str(idx)
ans = uoqbio kAfwcx rn

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

製品

リリース

R2020a

質問済み:

2020 年 4 月 21 日

コメント済み:

2020 年 4 月 21 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by