【发布时间】:2016-04-28 17:32:37
【问题描述】:
目标是生成六个乐透号码,但显然它们必须是唯一的。不过,这必须以函数形式编写,以下是使用库的等价物:
(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 上很菜鸟(实际上只是编程菜鸟),而且我在提问时自己解决了这个问题,所以我将把它留在这里并向你们征求建议(更好的风格,其他算法...)
【问题讨论】:
标签: matlab function random-sample