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 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