function [trials, b1, b2, M]=xruin(p1, p2, p, frames, seed) % xruin(p1, p2, p, frames, seed) simulates the "gamblers ruin" game. % p1 your starting pile % p2 bank's starting pile % p probability that you will win any given trial % frames max number of frames for the generated movie - a frame size of % zero will cause no movie to be generated % seed seed for random number generator % % output is of the form [trials, b1, b2, M] % trials number of trials run till completion % b1 history of your pile - plot by bar(b1) % b2 history of bank pile - plot by bar(b2) % M movie matrix - play by movie(M) if p>1 | p<0 error('invalid value for p') end if p1<0 error('invalid value for p1') end if p2<0 error('invalid value for p2') end if frames<0 error('invalid value for frames') end rand('seed', seed); if frames>0 M=moviein(frames); end currentsize=50; b1=zeros(1,50); b2=b1; trials=0; b1(1)=p1; b2(1)=p2; while p1>0 & p2>0 trials=trials+1; if rand>p | p==0 p2=p2+1; p1=p1-1; else p1=p1+1; p2=p2-1; end if trials==currentsize b1=[b1 zeros(1, 50)]; b2=[b2 zeros(1, 50)]; currentsize=currentsize+50; end b1(trials+1)=p1; b2(trials+1)=p2; if frames>0 bar(p1) hold on bar(p2, 'r') if trials<=frames M(:, trials)=getframe end hold off end end index=length(b1); while b1(index)==0 index=index-1; end if p1==0 s='Bank'; index=index+1; else s='You'; end b1=b1(1:index); b2=b2(1:index); s=sprintf('%s won in %d trials', s, trials); disp(s) if trials>frames & frames>0 disp('Frames limit exceeded') end