乐透代码,以前的号码不能再出现,我该如何改进呢

问题描述 投票:0回答:1

我使用matlab编写这段代码,似乎逻辑有问题,但我不知道我错在哪里以及如何改进这一点。

我想写一个乐透代码,其中有六个数字,前六个数字的范围是1到38,最后一个数字的范围是1到8.这是我的代码

previous_number=randi([1,38],1,6)
last=randi([1,8],1,1) %produce the last number

for k =1:6    
    while  last== previous_number %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]

但我发现最后一个数字仍然会产生与前六个数字相同的数字,例如,

"1" 2 33 55 66 10 "1"

1“2”33 55 66 10“2” 为什么?我已经说过了

while  last==previous_number(k)
    last=randi([1,8],1,1)
    end   

如果我想用c或其他程序语言编写代码,我想我可以使用if,while和loop等,就像这个基本循环一样,我不能使用“ismemeber”或randperm。我怎么能重写代码?

如果我重写为

previous_number=randi([1,38],1,6)
last=randi([1,8],1,1) %produce the last number

for k =1:6    
    if  last== previous_number(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]

结果还会显示“1”2 21 12 13 22“1”

matlab random
1个回答
1
投票

这是因为您首先遍历数字,然后根据特定的当前迭代替换qazxsw poi,而不考虑先前的迭代。

例如,在你的示例数据中,认为last让你进入第六次迭代,发现last = 10等于10的last,所以你替换它。但现在它可以生成b(k),你将完成while循环和for循环。

解决方案是将1与你的所有向量进行比较,而不是迭代它:

last

[截至评论讨论:]

如果您仍想分别比较每个元素,可以这样做:

previous_number = b(1:6);
last = previous_number(1);
while ismember(last, previous_number)
    last = randi(8); %produce the last number
end
© www.soinside.com 2019 - 2024. All rights reserved.