2016-01-22 86 views
1

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

回答

1

樂透是基於秩序不起作用的排列。

% 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-置換或作爲沒有替換的採樣。」

0

另一種方法是使用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