How to create a random number as i asked below.
11 ビュー (過去 30 日間)
古いコメントを表示
Hello everyone here is my question;
i want to create a random number with 4 number of digits but it needs some speciality.I mean 1 number shouldnt repeat again.For example
2222 is wrong 1234 is correct.
it supposed to be between 1000 and 9999 and user should guess the number for example again lets say our number is; 1234 if i guess 1235 program should output +++- or if i wrote 2234 program should -++-.
Thanks for helps.
0 件のコメント
回答 (2 件)
dpb
2015 年 6 月 3 日
doc randperm
4 件のコメント
Salaheddin Hosseinzadeh
2015 年 6 月 3 日
編集済み: Salaheddin Hosseinzadeh
2015 年 6 月 3 日
I like James solution, it's easy. Just keep K as 9 and be aware that you probably wont have a 0 in your digits. You also don't want any repeated digits so, your smallest value will be 1234, up to 9876.
James Tursa
2015 年 6 月 3 日
If you want the 0 possibility but not begin with 0, here are two solutions:
% Only one randperm call but solution not quite uniform distribution
x = randperm(10) - 1;
if( x(1) )
x = x(1:4);
else
x = x(2:5);
end
% Slightly more randperm calls on average, solution is uniform
x = 0;
while( x(1) == 0 )
x = randperm(10) - 1;
end
x = x(1:4);
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!