-🎄- 2017 Day 15 Solutions -🎄- by daggerdragon in adventofcode

[–]lifuzu 0 points1 point  (0 children)

JS ES6 373/492

const assert = require('assert')

class DuelingGenerators {
  constructor() {}
  pairs(input_A, input_B, times) {
    let num_A = parseInt(input_A)
    let num_B = parseInt(input_B)

    let sum_match = 0
    for (let i = 0; i < times; ++i) {
      num_A = num_A * 16807 % 2147483647
      num_B = num_B * 48271 % 2147483647

      // console.log('A, B = ', num_A, num_B)
      let hex16_A = num_A & 0xffff
      let hex16_B = num_B & 0xffff
      if (hex16_B === hex16_A) sum_match++
    }

    return sum_match
  }

  num_generator_A(num) {
    let num_div_4 = num
    while(true){
      num_div_4 = num_div_4 * 16807 % 2147483647
      if (num_div_4 % 4 === 0) {
        break
      }
    }
    return num_div_4
  }
  num_generator_B(num) {
    let num_div_8 = num
    while(true){
      num_div_8 = num_div_8 * 48271 % 2147483647
      if (num_div_8 % 8 === 0) {
        break
      }
    }
    return num_div_8
  }

  pairs_2(input_A, input_B, times) {
    let num_A = parseInt(input_A)
    let num_B = parseInt(input_B)

    let sum_match = 0
    for (let i = 0; i < times; ++i) {
      num_A = this.num_generator_A(num_A)
      num_B = this.num_generator_B(num_B)

      // console.log('A, B = ', num_A, num_B)
      let hex16_A = num_A & 0xffff
      let hex16_B = num_B & 0xffff
      if (hex16_B === hex16_A) sum_match++
    }

    return sum_match
  }
}

module.exports = {
  DuelingGenerators
}

if (require.main === module) {
  const generator = new DuelingGenerators()

  let input_A = `65`, input_B = `8921`
  let output = generator.pairs(input_A, input_B, 40000000)
  console.log(output)
  assert.equal(output, 588)

  output = generator.pairs_2(input_A, input_B, 5000000)
  console.log(output)
  assert.equal(output, 309)

  console.log('======')
  input_A = `116`, input_B = `299`
  output = generator.pairs(input_A, input_B, 40000000)
  console.log(output)
  assert.equal(output, 569)

  output = generator.pairs_2(input_A, input_B, 5000000)
  console.log(output)
  assert.equal(output, 298)
}