How to stop a rand function from getting the same result in a for loop

3 ビュー (過去 30 日間)
Cooper Mathews
Cooper Mathews 2020 年 5 月 2 日
コメント済み: Mehmed Saad 2020 年 5 月 2 日
Hey guys basic question.
I have this code here and i want to print the card deck in a random order:
for x = 1:52
y = randi([1 52]);
if y == 1
fprintf('%s\n','Spade Ace')
elseif y == 2
fprintf('%s\n','Spade 2')
(continues through the whole card deck 1-52)
elseif y == 51
fprintf('%s\n','Clubs Queen')
else
fprintf('%s\n','Clubs King')
end
end
Is there a way I can stop the rand function from comming up with the same number?

回答 (2 件)

Walter Roberson
Walter Roberson 2020 年 5 月 2 日
cards = {'Spade Ace', 'Spade 2', 'Spade 3' up to 'Clubs Queen', 'Clubs King'};
x = randperm(52);
fprintf('%s\n', cards{x});
No loop needed. rand() not explicitly used (it is used inside of randperm)

Mehmed Saad
Mehmed Saad 2020 年 5 月 2 日
編集済み: Mehmed Saad 2020 年 5 月 2 日
I dont know how to stop rand function from comming up with same number but there is a way you can do that by indexing and removing numbers.
z = 1:52;
x = zeros(1,52);
for i =1:52
y = randi([1 length(z)]);%
x(i) = z(y);
z(y) = [];
end
This will generate random number without repeating them
I stored all the values in x, to check if they are right type following in command window
sort(x)
it will be from 1:52 without any repeatition

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by