Randomize a string from input

10 次查看(过去 30 天)
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

采纳的回答

Roger Stafford
Roger Stafford 2018-1-11
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 个评论
Mitul Dattani
Mitul Dattani 2018-1-11
Wicked thankyou! I'm so silly aha
Roger Stafford
Roger Stafford 2018-1-12
@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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by