Randomize a string from input

10 visualizaciones (últimos 30 días)
Mitul Dattani
Mitul Dattani el 11 de En. de 2018
Comentada: Roger Stafford el 12 de En. de 2018
From a past paper theres a question that asks for a string, then the blank spaces, then the first word, the to randomize the first word. I managed to do all of it except randomize the last word. I've put my code below not exactly too sure what to put here, pretty sure what I've put is wrong.
str=input('Give a string: ')
[m, n] = size(str);
C = 0;
for i = 1:n
if str(i) == ' '
C=C+1;;
pos_blanks(C) = i;
end
end
pos_blanks
first_word = str(1:pos_blanks(1)-1);
first_word
perm_of_first_word = randi(first_word);
perm_of_first_word

Respuesta aceptada

Roger Stafford
Roger Stafford el 11 de En. de 2018
To obtain a random permutation of 'first_word' you need the 'randperm' function, not 'randi':
perm_of_first_word = first_word(randperm(length(first_word)));
  2 comentarios
Mitul Dattani
Mitul Dattani el 11 de En. de 2018
Wicked thankyou! I'm so silly aha
Roger Stafford
Roger Stafford el 12 de En. de 2018
@Mitul Dattani: Here is how you can do the whole problem, which, as I understand it, is to randomly permute the characters within each of the "words" in a given input string:
str = input('Give a string: ');
pstr = str; % pstr will receive the permuted result
d = diff([false,str~=' ',false]); % For comparing successive characters
f1 = find(d>0); % Indices of first character in each word
f2 = find(d<0)-1; % Indices of final character in each word
for k = 1:length(f1) % Loop once for each word
w = str(f1(k):f2(k)); % Get the k-th word
pstr(f1(k):f2(k)) = w(randperm(f2(k)-f1(k)+1)); % Randomly permute its characters
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices 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!

Translated by