Creating a Wordscramble using matlab
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
AJ Schmidt
el 21 de Abr. de 2020
Comentada: Stephen23
el 21 de Abr. de 2020
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
0 comentarios
Respuesta aceptada
Ameer Hamza
el 21 de Abr. de 2020
Editada: Ameer Hamza
el 21 de Abr. de 2020
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 comentarios
Stephen23
el 21 de Abr. de 2020
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Identification en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!