JSFiddle - React, Tailwind, and code Playground

by ai_enabled

HTML

<html>
<body>
Please open the console to see the results.
</body>
</html>

JavaScript

const N = 1000;
const probability = 1 / N;
const players = 10000;
const bucketSize = 200;

const { random, floor } = Math;
function tryit() {
	let count = 0;
	while (true) {
		++count;
		if (random() < probability) {
			return count;
		}
	}
}

function median(values){
	values.sort(function(a,b){
  	return a-b;
  });
  var half = Math.floor(values.length / 2);
  
  if (values.length % 2)
  	return values[half];
  else
  	return (values[half - 1] + values[half]) / 2.0;
}

let buckets = [];
let allResults = [];
var totalRolls = 0.0;
var unluckyPlayers = 0.0;

for (let ii = 0; ii < players; ++ii) {
	let num_rolls = tryit();
	let bucket = floor(num_rolls / bucketSize);
	buckets[bucket] = (buckets[bucket] || 0) + 1;
  totalRolls += num_rolls;
  allResults[ii] = num_rolls;
  if (num_rolls > 2*N)
  {
    unluckyPlayers++
  }
}

for (let ii = 0; ii < buckets.length; ++ii) {
	console.log(`${ii*bucketSize}-${(ii+1)*bucketSize}: ${buckets[ii] || 0}`);
}

console.log(`Average number of attempts: ${totalRolls/players}`);
console.log(`Median number of attempts: ${median(allResults)}`);
console.log(`Unlucly players (needed more than 2*N attempts): ${100 * unluckyPlayers/players}%`);