您需要滚动次数的期望是什么

时间:2016-01-14 14:08:05

标签: matlab

我有兴趣用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)

1 个答案:

答案 0 :(得分: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次,输出试验会告诉我每次获得所有六个数字需要多少掷骰子。您可以在此周围添加时钟来测量时间。