Randomize a string from input
7 次查看(过去 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
0 个评论
采纳的回答
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 个评论
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 Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!