% Mousetrap simulation % %User input for probability of hitting a trap.; p = input('Probability of a hit: p = '); %Initialize the number of balls in the air, b, the generation time, i,; %and the matrix and vector of unsprung traps, mt and xmt, respectively; b = 1; i = 0; mt = ones(10,10) xmt = mt(:); %Compute the total number of unsprung traps.; u = sum(xmt); fprintf(' Unsprung Traps = %3.0f, Balls in the Air = %2.0f\n',u,b) pause %Strike any key to continue. %Loop for continuing the process until no balls are in the air.; while b > 0 %Increase the generation time.; i = i+1; %Use a random number generator to determine how many traps are hit.; th1 = (rand(1,b)<=p*ones(1,b)); th2 = th1(:); th = sum(th2); %Use the random number generator to determine exactly which traps are; %hit between 1 and 100.; c1 = ceil(100*rand(1,th)); c2 = c1(:); %Compare how many balls are released based on unsprung traps and; %transform those traps to ones which are sprung.; b = 2*sum(xmt(c2)); xmt(c2) = 0*xmt(c2); mt = reshape(xmt,10,10) u = sum(xmt); fprintf(' Unsprung Traps = %3.0f, Balls in the Air = %2.0f\n',u,b) pause %Strike any key to continue. end fprintf(' Generations = %2.0f\n',i)