% Some simple probability experiments in Matlab

% Toss a coin 
x=rand<.5

% Roll a die
x=ceil(6*rand)

% Toss a coin a bunch of times
n=10
x=rand(1,n)<.5

% Toss a coin a bunch of times; count the number of heads
n=10
t=rand(1,n)<.5; x=sum(t)

% Roll a die a bunch of times; make a histogram
n=10
x=ceil(6*rand(1,n)); hist(x,1:6)

% Toss a coin a bunch of times many times
clear
p=.7
n=100
trials=10000
x=zeros(1,trials);
for i=1:trials
    t=rand(1,n)<p;
    x(i)=sum(t);
end
hist(x,0:n)

% Deal a poker hand.
deck=randperm(52);
hand=deck(1:5)

% Birthday problem.
reps=1000
rec=NaN(1,reps);

days=365
people=23
for k=1:reps
    dates=ceil(rand(1,people)*days);
    rec(k)=length(unique(dates));
end
frac=sum(rec<people)/reps

% Coupon collector problem
reps=1000
rec=NaN(1,reps);

n=100
m=ceil(n*(log(n)+log(1/log(2))))
for k=1:reps
    coupons=ceil(rand(1,m)*n);
    collection=unique(coupons);
    rec(k)=length(collection);
end
gotall=sum(rec==n)/reps

% Secretary problem.
n=100
for k=1:n-1
  s=sum(1./[k:n-1]);
  if s<=1
      break
  end
end
k % pass over the first k-1
reps=10^4
rec=NaN(1,reps);

for r=1:reps
    a=randperm(n);
    comp=min(a(1:k-1));
    sec=a(n); % Last resort
    for i=k:n-1
        if a(i)<comp
            sec=a(i);
            break
        end
    end
    
    rec(r)=sec;
end

successrate=sum(rec==1)/reps


% Having any ace is good.

reps=10^4
rec=NaN(1,reps);

k=0;

while(k<reps)
    hand=sort(randsample(52,13)');
    aces=sum(hand<=4);
    
    if aces>=1
        k=k+1;
        rec(k)=aces;
    end
    
end

hist(rec,0:4)
meansaces=mean(rec)
       

% Having the aces of spades is better.

reps=10^4
rec=NaN(1,reps);

k=0;

while(k<reps)
    hand=sort(randsample(52,13)');
    aces=sum(hand<=4);
    
    if hand(1)==1
        k=k+1;
        rec(k)=aces;
    end
    
end

hist(rec,0:4)
meanaces=mean(rec)

