フィルターのクリア

Using randperm function for a string

3 ビュー (過去 30 日間)
Daniel Gollin
Daniel Gollin 2020 年 7 月 15 日
回答済み: Walter Roberson 2020 年 7 月 15 日
For an assignment i need to use the randperm function to jumble a word. For example take the word 'amazing' and jumble it to 'zamigna'. I am pretty sure I need to specify the randomization of an array where each integer is attached to a letter but am not sure on the syntax on how to do that.
for reference here is the code I have as of now (I know there is still a lot missing/incorrect)
function solved = solveOneJumble(word)
% solveOneJumble
%
% Takes one argument (the word to guess), creates a jumble out of it,
% and repeatedly allows the user to guess the word (or quit guessing).
%
% Input:
% word the word the user is to guess
%
% Output: true (1) if the jumble was correctly solved;
% false (0) otherwise (i.e., the user decided to quit)
%
solved = 0;
correctWord = word;
word = randperm((word));
while ~solved
if randperm((word)) == word
word = randperm((word));
else
guessedWord = input('Enter guess or Q to quit: ');
if guessedWord == 'Q'
disp('The word was ',correctWord)
elseif guessedWord ~= correctWord
guessedWord = input('Enter guess or Q to quit: ');
else
disp('Correct')
solved = 1;
end
end
end

回答 (1 件)

Walter Roberson
Walter Roberson 2020 年 7 月 15 日
Are you sure that word will be datatype string() and not character vector?
guessedWord = input('Enter guess or Q to quit: ');
input() with no 's' option evaluates what the user types, so the user would have to type '' or "" around their input. Consider using the 's' option, which would return a character vector
if guessedWord == 'Q'
You should not rely upon the user having deliberately entered a string object: even if they remember that they need to enter characters, there is too much chance they might user '' instead of "" . And if they do, then using == 'Q' is not going to work like you want. When you compare a character vector to a scalar character, the test is equivalent to
if all(all(guessedWord == repmat('Q', size(guessedWord))))
If you knew that guessedWord was a string() object then the string == operator would be invoked instead of the character == operator. Or if you had used
if guessedWord == "Q"
then it would be the string() == operator.
word = randperm((word));
That should be something like
cword = char(word);
cword = cword(randperm(length(cword)));
if ischar(word)
word = cword;
else
word = string(cword);
end

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by