函数形式的MATLAB randsample
问题描述:
目标是生成六个乐透号码,但显然它们必须是唯一的。这在函数形式写入不过,使用该库相当于以下内容:函数形式的MATLAB randsample
(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-置换或作为没有替换的采样。”
答
另一种方法是使用rejection sampling:独立生成数字,如果它们不是全部不同,则重新开始。只要数字没有差异的机会很小,这是有效的。
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