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

조회 수: 6 (최근 30일)
Jacob Stamm
Jacob Stamm 2019년 5월 16일
댓글: Jacob Stamm 2019년 5월 16일
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)
Jos (10584) 2019년 5월 16일
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
  댓글 수: 1
Jacob Stamm
Jacob Stamm 2019년 5월 16일
Got it! Thank you, much appreciated. (Your code is so much cleaner btw).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by