Randomize a string from input

10 ビュー (過去 30 日間)
Mitul Dattani
Mitul Dattani 2018 年 1 月 11 日
コメント済み: Roger Stafford 2018 年 1 月 12 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by