2016-01-14 20 views
1

我有興趣使用Matlab編寫一些東西來模擬擲骰子所需的次數。 (也許重做只有一次?)你需要滾動的次數的期望是什麼

我需要不斷重新擲骰子,直到出現一個唯一的數字。 下面是我到目前爲止的代碼。

任何幫助表示讚賞。

% N: the max number a roll of the fair die can take  
N = 6; 

% M: number of trials. Each trial is a sequence of rolls, and it 
% terminates once you see K N's in a row. 
M = 1; 
K = 1; 

% initialize the trials vector. The m-th entry is going to store 
% the number of rolls performed in the m-th trial. 
trials = zeros(M,1); 

% t0: record the start time of the simulation 
t0 = clock(); 

% This for loop is to run the M trials. 
for m = 1:M 

    % collection: sequence of rolls. It's initialized with K 
    % samples drawn from a uniformly distributed integer random 
    % variable, because the minimal length of collection has to 
    % be K. 

    % Here begins the loop to roll the die until all 6 numbers appear 
    % If any number is repeated, re-roll until a unique number appears & move on to the next number 
    collection = randi(N,K,1); 
    collection(:,2) = randi(N,K,1); 
    if collection(:,2)~=collection(:,1) 
     collection(:,3) = randi(N,K,1) 
    else collection(:,2) = randi(N,K,1) 
    end 

    if collection(:,3)~=(collection(:,1) && collection(:,2)) 
     collection(:,4) = randi(N,K,1) 
    else collection(:,3) = randi(N,K,1) 
    end 

    if collection(:,4)~=(collection(:,1)&& collection(:,2) && collection(:,3)) 
     collection(:,5) = randi(N,K,1) 
    else collection(:,4) = randi(N,K,1) 
    end 

    if collection(:,5)~=(collection(:,1)&& collection(:,2) && collection(:,3) && collection(:,4)) 
     collection(:,6) = randi(N,K,1) 
    else collection(:,5) = randi(N,K,1) 
    end 

    if collection(:,6)=(collection(:,1)&& collection(:,2) && collection(:,3) && collection(:,4) && collection(:,5)) 
     collection(:,6) = randi(N,K,1) 
    end 

    % now that the last K rolls are all N's, we take note of the number 
    % of rolls performed in this trial 
    trials(m) = length(collection); 
end 

% we measure how much time the simulation has spent by 
% computing the time difference between now and t0 
elapsed_time = etime(clock(), t0) 

% the Monte Carlo estimate, which should be close to your analytical 
% solution. 
mean(trials) 
+2

請解釋代碼應該做什麼。 – Daniel

+1

你確定它必須是'collection(:,6)=(collection(:,1)...)'?一個'='是一個賦值,即'collection(:,6)'將被設置爲右側的值。比較將會是'==' – hbaderts

+0

你確定它必須是'collection(:,3)〜=(collection(:,1)&& collection(:,2))'?如果您想檢查第3列是否與第1列不同並且與第2列不同,則應將其寫爲'(collection(:,3)〜= collection(:,1))&(collection(:,3) 〜= collection(:,2))' – Lior

回答

1

這裏是我會怎麼做

function trials = diceExperiment(M) 
trials = zeros(1,M); 
for i = 1:M 
    missingNum = true(1,6); % None of the six numbers are seen yet 
    while (any(missingNum)) 
     currentNum = randi(6,1); 
     trials(i) = trials(i)+1; 
     missingNum(currentNum) = false; 
    end 
end 
end % End of function 

這將運行這個實驗M次,輸出審判會告訴我該怎麼骰子的許多卷它採取每次得到所有六個數字。你可以添加你的時鐘東西來測量時間。

+0

好吧,它的作品!!!!!!非常感謝=) – kimboon