I tried to do a in Javascript a birthday paradox event for 23 students, it should give me an average probability of 51% but it always give me number around 67%. Here the code:
var pers = [];
var D = 0;
for (var i = 0; i < 10000; i++) {
for (var k = 0; k < 23; k++) {
pers.push(Math.floor((Math.random()*366) + 1));
}
var npers = pers.slice();
npers.sort();
for ( var v = 0; v < npers.length; v++ ) {
if (npers[v-1] == npers[v]) {
D++;
}
}
pers = [];
}
D = D / 100;
var DD = D.toString();
DD = DD + "%";
document.write(DD);
Could you,please, tell me where I committed a mistake ? Thank you very much. I'm sure that I've committed a mistake because the lowest percentage that I got was 66%, well over the 51% goal. (I've ran it several times). Thank you again for your help, it's been hours that I'm trying to figure out what I got wrong but I can't get it.
You count the number of all coincidences, not the number of cases where there are at least one coincidence in the room. That is, if on a given set there are, say, three people such that they share a birthday, or two pairs of people sharing birthdays, you increment
D
twice.Add a
break;
afterD++;
and you'll get numbers around 50%.By the way, your
v
loop underindexesnpers
(atv=0
, you comparenpers[-1]
againstnpers[0]
) - but that does not affect the result.