目标是生成六个乐透号码,但显然它们必须是唯一的。不过,这必须以函数形式编写,以下是使用该库的等效项:
(randsample(42,6))'
我的想法是创建具有所有可能性的向量,通过索引一次选择一个,并且在选择下一个向量之前将其抓取出来,使其无法再次选择。
function numbers = lottonumbers()
pool = 1:42;
numbers = zeros(1,6);
for i=1:6
for j=42-i
randIndex = round(1+j*rand);
randNumber = pool(randIndex);
numbers(i) = randNumber;
if randIndex==1
pool = pool(2:end);
else if randIndex==length(pool)
pool = pool(1:(end-1));
else
pool = [pool(1:randIndex-1), pool(randIndex+1:end)];
end
end
end
end
由于我在 MATLAB 是相当菜鸟(真的只是编程的菜鸟),并且因为我在提问时自己解决了这个问题,所以我就把它留在这里,向你们征求建议(更好的风格,其他算法......
乐
透基于顺序不起作用的排列。
% p = randperm(n,k) returns a row vector containing k unique integers selected randomly from 1 to n inclusive.
randperm( 42, 6 )
应该做这个伎俩。
来自代码:"这有时被称为 1:N 的 K 排列或无替换的采样。
另一种方法是使用拒绝采样:独立生成数字,如果它们不是全部不同,则重新开始。只要数字不完全不同的几率很小,这就会有效。
N = 6;
M = 42;
done = false;
while ~done
result = randi(M,1,N); %// generate N numbers from [1,...,M]
done = all(diff(sort(result))); %// if all are different, we're done
end