目標是生成六個樂透號碼,但顯然它們必須是唯一的。這在函數形式寫入不過,使用該庫相當於以下內容:函數形式的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(在編程只是小白真的)很小白,因爲我解決了它自己,同時問這個問題,我只是要離開這裏,並問你們的建議(更好風格,其他算法...)