Counter game

  • + 0 comments

    Javascript (ugly, non-math-based version)

    function counterGame(n: number): string {
      const powersOfTwo = [1];
      let player = 'Richard';
      
      while (n !== 1) {
        player = player === 'Louise' ? 'Richard' : 'Louise';
        
        while (powersOfTwo[powersOfTwo.length-1] < n) {
          powersOfTwo.push(powersOfTwo[powersOfTwo.length-1] * 2);
        }
        
        if (powersOfTwo.includes(n)) {
          n /= 2;
        } else if (n !== 1) {
          let nextLowestPowOfTwo;
          for (let i=0; i < powersOfTwo.length; i++) {
            if (powersOfTwo[i] > n) {
              nextLowestPowOfTwo = powersOfTwo[i-1];
              break;
            }
          }
          n -= nextLowestPowOfTwo
        }
      }
      
      return player;
    }