From 7ed737b9a2f4e65d8a7db13a82f1c1eb611b5616 Mon Sep 17 00:00:00 2001 From: Kegan Myers Date: Sun, 13 Dec 2020 00:52:19 -0600 Subject: [PATCH] solve 2020d13 --- data/2020/13.txt | 2 ++ solutions/2020/13.js | 56 ++++++++++++++++++++++++++++++++++++++++++++ testAll.js | 1 + 3 files changed, 59 insertions(+) create mode 100644 data/2020/13.txt create mode 100644 solutions/2020/13.js diff --git a/data/2020/13.txt b/data/2020/13.txt new file mode 100644 index 0000000..d9d9da3 --- /dev/null +++ b/data/2020/13.txt @@ -0,0 +1,2 @@ +1005595 +41,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,37,x,x,x,x,x,557,x,29,x,x,x,x,x,x,x,x,x,x,13,x,x,x,17,x,x,x,x,x,23,x,x,x,x,x,x,x,419,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,19 \ No newline at end of file diff --git a/solutions/2020/13.js b/solutions/2020/13.js new file mode 100644 index 0000000..f06e11e --- /dev/null +++ b/solutions/2020/13.js @@ -0,0 +1,56 @@ +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; + } + }, +}; diff --git a/testAll.js b/testAll.js index a97b45e..fb37a63 100644 --- a/testAll.js +++ b/testAll.js @@ -14,6 +14,7 @@ const results = { 10: [2277, 37024595836928], 11: [2359, 2131], 12: [508, 30761], + 13: [2095, 598411311431841], }, 2019: { 1: [3386686, 5077155],