Using randperm function for a string

18 views (last 30 days)
Daniel Gollin
Daniel Gollin on 15 Jul 2020
Answered: Walter Roberson on 15 Jul 2020
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

Answers (1)

Walter Roberson
Walter Roberson on 15 Jul 2020
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

Tags

Community Treasure Hunt

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

Start Hunting!