Created
December 13, 2022 19:41
-
-
Save kevinleedrum/1367306153eb2cba1d0fad551d65bbca to your computer and use it in GitHub Desktop.
Advent of Code 2022 - Day 13
This file contains hidden or 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 INPUT = `...`; | |
(function doPart1() { | |
const pairs = INPUT.split(/\n\n/).map((p) => | |
p.split(/\n/).map((l) => eval(l)) | |
); | |
const correctIndices = pairs | |
.filter((p) => comparePackets(...p) < 0) | |
.map((p) => pairs.indexOf(p) + 1); | |
console.log(correctIndices.reduce((a, b) => a + b, 0)); | |
})(); | |
(function doPart2() { | |
const DIVIDERS = [[[2]], [[6]]]; | |
let packets = INPUT.split(/\n/) | |
.filter(Boolean) | |
.map((p) => eval(p)); | |
packets.push(...DIVIDERS); | |
packets.sort(comparePackets); | |
console.log( | |
DIVIDERS.map((d) => packets.indexOf(d) + 1).reduce((a, b) => a * b, 1) | |
); | |
})(); | |
function comparePackets(l, r) { | |
if ([l, r].every((a) => !Array.isArray(a))) return l - r; | |
[l, r] = [l, r].map((a) => (Array.isArray(a) ? a : [a])); | |
for (let i = 0; i < Math.max(l.length, r.length); i++) { | |
if (l[i] === undefined) return -1; | |
if (r[i] === undefined) return 1; | |
if (l[i] === r[i]) continue; | |
const cmp = comparePackets(l[i], r[i]); | |
if (cmp !== undefined) return cmp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment