# How to output random number each time a for loop repeats?

11 views (last 30 days)
Jacob Stamm on 16 May 2019
Commented: Jacob Stamm on 16 May 2019
Hello, I'm trying to write a code that will ask for an input string from the user (like "Hello", for example), and generate random characters until it guesses the string you entered. Normally this code would take a long time to run, so I (tried) to make it so if it guesses a correct letter in the right spot (like the e in the second position of Hello) then it would stick there and continue guessing the remaining 4 letters until it gets the whole thing.
My problem is that the way I generate the random numbers is causing multiple letters to be randomly changed in unison. So for example when I enter 'hello' it outputs:
mqHdo
ieHBo
oemto
ueHru
fefkf
AeAPA
IeIuI
MeMCM
GeGOG
ZeZqZ
So the first guess seems alright but for some reason the last letter and first letter get 'matched up' and gets randomly mapped to the same letter. Also, the o was correct from the beginning, but it gets switched to a u at some point. I do not know why this is happening. Eventually the code spits out 5 digit strings of the same letter cycling through random letters.
To fix this, I tried throwing in rng('shuffle') to try to reset the random number generator between iterations of the loop but the problem still persists.
clear
clc
prompt = 'Enter the sentence you would like to be generated: ';
input = input(prompt,'s');
inputlength = length(input);
symbols = ['a':'z' 'A':'Z' ' '];
nums = randi(numel(symbols),[1 inputlength]);
random = symbols (nums);
compare = input == random;
comparenumber=double(compare);
disp(random)
truth=true([1 numel(compare)]);
while sum(comparenumber) < numel(compare)
pause (1)
for i = 1:inputlength
compare = input == random;
comparenumber=double(compare);
if compare(i) == 0
random=strrep(random,random(i),symbols(randi(numel(symbols))));
end
end
disp(random)
end

Jos (10584) on 16 May 2019
You can use an extra variable to keep track of the letters that were guessed correctly.
InputString = 'hello'
N = numel(InputString) ;
QC = false(1,N) ; % extra variable
while ~all(QC)
RandomString = ... % I leave it up to you to return a random string of N characters
RandomString(Q) = InputString(Q) ; % some letters are known already
disp(RandomString)
QC = RandomString == InputString ; % compare letter by letter
end
Jacob Stamm on 16 May 2019
Got it! Thank you, much appreciated. (Your code is so much cleaner btw).

R2017b

### Community Treasure Hunt

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

Start Hunting!