Answer on Question #45468,
Programming, Mat LAB | Mathematica | MathCAD | Maple
Problem.
If there is a group of n people in a room, what is the probability that two or more of them having same birthday? It is possible to determine answer to this question by simulation. (Hint: You can generate random dates, n times and determine the fraction of people who born in a given day). Write a function that determines the answer to this question by simulation. The program you write can take n as the input and prints out the probability that two or more of n people will have the same birthday for n=2,3,4... 40...Flow chart also.
Solution.
Code (MATLAB)
function probability()
clc();
% Data for graphic
peopleArray = [];
probabilityArray = [];
% Input
n = input('The maximal number of people: ');
m = input('The number of simulations: ');
for i = 1:1:n
% The number of successful simulations
% (when there is two or more people with same birthday date)
simSuc = 0;
% Simulation loop
for j = 1:1:m
simGrp = randi(365, 1, i);
if length(unique(simGrp)) ~= i
simSuc = simSuc + 1;
end
end
% Output
fprintf('The probability equals %f (%d simulations and %d people)\n', simSuc/m, m, i);
% Data for graphic
peopleArray = [peopleArray i];
probabilityArray = [probabilityArray simSuc/m];
end
%Graphic
plot(peopleArray, probabilityArray)
endResult
Graphic
Flowchart (http://code2flow.com/abzxt8)