Find all 52 cards - one random card at the time

How many iterations before you've found each card at least once

by jonahe

JavaScript

let cards = Array.from({length: 52}).map((_,i) => i + 1);

const getRandomCard = () => {
	const index = Math.floor((Math.random() * cards.length));
  return cards[index];
};

const runExperiment = ({printLog}) => {
	let foundCards = [];
  
  const hasFoundEveryCard = () =>  cards.every(uniqueCard => foundCards.includes(uniqueCard));
  
  while(!hasFoundEveryCard()) {
  	foundCards.push(getRandomCard());
  }
  printLog && console.log(`Found one of each card after ${foundCards.length} tries`);
  // console.log( foundCards.sort((a,b) => a > b ? 1 : a === b ? 0 : -1).join());
  return foundCards.length;
}



const getAverageTries = numOfExperiments => {
	const tries = [];
  for(let i = 0; i < numOfExperiments - 1; i++) {
    const triesToSucceed = runExperiment({printLog: false});
    tries.push(triesToSucceed);
  }
  
  const totalTries = tries.reduce((acc, next) => {
  	return acc + next;
	}, 0);
  return totalTries / tries.length;
}

console.log(getAverageTries(500))

// There is also a formula stating that
// the answer should be    N * "the N:th harmonic number", where
// the nth H === 1 + 1/2 + 1/3 + 1/4 + ... + 1/n
// Cred: https://www.reddit.com/r/askscience/comments/6y93j8/if_you_were_to_randomly_find_a_playing_card_on/dmlly16/

const nthHarmonicNum = n => {
	let H = 1;
  for(let i = 2; i <= n; i++) {
  	H += 1 / i;
  }
  return H;
}

const harmonicNum = nthHarmonicNum(52);

console.log(`The theorectic answer is ${harmonicNum} * ${cards.length} = ${ harmonicNum * cards.length}`);