MATLAB Answers

0

Lotto code,the previous number cannot appear again,how do i improve it?

yang-En Hsiao さんによって質問されました 2019 年 3 月 6 日
最新アクティビティ yang-En Hsiao さんによって コメントされました 2019 年 3 月 6 日
i want to write a lotto code,and there are six numbers in it,the range of first six numbers is 1 to 38,the range of last number is 1 to 8.Here is my code
x = rand(1,10);
[a b]=sort(x);
previous_number=b(1:6)
last=randi([1,8],1,1) %produce the last number
for k =1:6
while last== b(k)%while that last number is the same as the value of one of the previous number
last=randi([1,8],1,1)%then produce the last number again,until the different value produce
end
end
ltto=[previous_number last]
but i found that the last number will still generate the same number as the first six numbers,for example,
"1" 2 33 55 66 10 "1"
1 "2" 33 55 66 10 "2"
Why?i have already said
while last== b(k)
last=randi([1,8],1,1)
end
how do i improve it? i don't want to use the "randperm"

  0 件のコメント

サインイン to comment.

タグ

1 件の回答

回答者: Torsten
2019 年 3 月 6 日
編集済み: Torsten
2019 年 3 月 6 日
 採用された回答

x = rand(1,10);
[a b] = sort(x);
previous_number = b(1:6)
set_for_last_number = setdiff(1:8,previous_number);
pos = randi(length(set_for_last_number));
last = set_for_last_number(pos)

  3 件のコメント

yang-En Hsiao 2019 年 3 月 6 日
your answer is great,but if i can't use the setdiff,maybe because the version is too old,how do i write this code by using maybe like while ,for or if loop?
madhan ravi
2019 年 3 月 6 日
Wow yang why is it so hard to admit that it’s your homework?
yang-En Hsiao 2019 年 3 月 6 日
because i think i can't rely on the matlab functions too much,although they are very convenient.I believe it can be written even we don't use the function like " setdiff " or " randperm " .Like C or other programs,there is no so convenient function like " setdiff " and " randperm "

サインイン to comment.



Translated by