News for hackers. Stuff that matters.
Re:The Joy of Coding: Observable by elwell on Thursday January 30, 2020 @12:07PM (#22193008)
here's a js brute-force for question 1 and 3:

    const cards = [...Array(13).keys()];
    const standardDeck = Array(4).fill().reduce((acc, v) => {
      return acc.concat(cards);
    }, []);
    
    const makeShuffledDeck = () => {
      const deckInst = standardDeck.slice();
      const shuffledDeck = [];
      while (deckInst.length) {
        const removeIdx = Math.floor(Math.random() * deckInst.length);
        shuffledDeck.push(deckInst[removeIdx]);
        deckInst.splice(removeIdx, 1);
      }
      
      return shuffledDeck;
    };
    
    const numDrawsNeeded = () => {
      const counts = Array(13).fill(0);
      const deck = makeShuffledDeck();
      
      while (deck.length) {
        const card = deck.pop()
        if (++counts[card] === 4) {
          return standardDeck.length - deck.length;
        }
      }
      
      throw "Drew all cards, but never found 4 of a kind.";
    };

    // average
    const numTrials = 10000;
    console.log([...Array(numTrials)].map(numDrawsNeeded).reduce((acc, v) => {
      return acc + v;
    }, 0) / numTrials);
    
    /*
    // max
    const numTrials = 10000;
    console.log([...Array(numTrials)].map(numDrawsNeeded).reduce((acc, v) => {
      return Math.max(acc, v);
    }, 0));
    */

There are no comments on this comment yet.