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

5 ビュー (過去 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 Center および File ExchangeLoops 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