jsadvent/solutions/2020/13.js

57 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-12-13 06:52:19 +00:00
const { Glib, BNMath: Math, fn } = require('../../lib');
const parse = (input) => {
const [arrivalString, idStrings] = input.split('\n');
return {
arrival: BigInt(arrivalString),
ids: Glib.fromSplit(idStrings, ',').map((s) =>
s === 'x' ? 1n : BigInt(s),
),
};
};
const departureAfter = (time, id) => {
let next = (time / id) * id;
return next < time ? next + id : next;
};
module.exports = {
'1': (input) => {
input = parse(input);
return input.ids
.flatMap((i) => {
if (i === 1n) {
return [];
}
return [[i, departureAfter(input.arrival, i) - input.arrival]];
})
.minScore()
.glib.product();
return id * (time - input.arrival);
},
'2': (input) => {
input = parse(input).ids.array;
let solved = 1n;
let step = input[0];
let start = departureAfter(0n, input[0]);
while (true) {
for (let i = solved; i < input.length; i++) {
const currentBus = input[i];
const currentTime = start + i;
if (departureAfter(currentTime, currentBus) === currentTime) {
solved += 1n;
step *= currentBus;
} else {
break;
}
}
if (solved == input.length) {
return start;
}
start += step;
}
},
};