Last active
December 15, 2020 15:11
-
-
Save warriordog/4e2b79266851306f356ffe82519fff82 to your computer and use it in GitHub Desktop.
Solution to Advent of Code 2020 Day 13 Part 2 that uses a sieve algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { parseInputFile } = require('../utils/parser'); | |
/** | |
* Performs a negative-aware modulus operation. | |
* @param {number} a | |
* @param {number} n | |
* @returns {number} | |
*/ | |
function absmod(a, n) { | |
while (a < 0) { | |
a += n; | |
} | |
return a % n; | |
} | |
// parse inputs | |
const inputs = parseInputFile('day13-input.txt', /(?:^|,)([\dx]+)(?=,|$)/gm) | |
// skip the first line of the input | |
.slice(1) | |
// parse into object | |
.map(([, id], i) => ({ id: parseInt(id.trim()), i })) | |
// skip 'unconstrained' busses | |
.filter(bus => !Number.isNaN(bus.id)) | |
// sort in descending order by id | |
.sort((b1, b2) => b2.id - b1.id) | |
// convert to bigints | |
.map(bus => ({ id: BigInt(bus.id), offset: BigInt(absmod(bus.id - bus.i, bus.id)) })); | |
let cN = inputs[0].id; | |
let cA = inputs[0].offset; | |
for (let i = 1; i < inputs.length; i++) { | |
const bus = inputs[i]; | |
while (cA % bus.id !== bus.offset) { | |
cA += cN; | |
} | |
cN *= bus.id; | |
} | |
// Expected: 556100168221141 | |
console.log(`Part 2: the timestamp is ${ cA }`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment