Created
December 13, 2022 12:31
-
-
Save ivandashk/474775a365221cbe284c654945f1098a to your computer and use it in GitHub Desktop.
Advent of Code 22 — 13b
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 fs = require('fs'); | |
const readline = require('readline'); | |
function compare(left, right) { | |
for (let i = 0; i < Math.max(left.length, right.length); i++) { | |
let leftValue = left.at(i); | |
let rightValue = right.at(i); | |
if (leftValue === undefined) return -1; | |
if (rightValue === undefined) return 1; | |
if (Number.isInteger(leftValue) && Number.isInteger(rightValue)) { | |
if (leftValue !== rightValue) { | |
return leftValue - rightValue; | |
} | |
} else { | |
if (Number.isInteger(leftValue)) leftValue = [leftValue]; | |
if (Number.isInteger(rightValue)) rightValue = [rightValue]; | |
return compare(leftValue, rightValue); | |
} | |
} | |
} | |
async function processLineByLine(file) { | |
const fileStream = fs.createReadStream(file); | |
const rl = readline.createInterface({ | |
input: fileStream, | |
crlfDelay: Infinity | |
}); | |
let iteration = 0; | |
const cases = []; | |
for await (const line of rl) { | |
if ([0, 1].includes(iteration % 3)) { | |
cases.push(JSON.parse(line)); | |
} | |
iteration++; | |
} | |
const first_injection = [[2]]; | |
const second_injection = [[6]]; | |
cases.push(first_injection, second_injection); | |
cases.sort(compare); | |
const idx_first_inj = cases.indexOf(first_injection) + 1; | |
const idx_second_inj = cases.indexOf(second_injection) + 1; | |
console.log(`${file}: ${idx_first_inj * idx_second_inj}`); | |
} | |
processLineByLine('13.test.txt'); | |
processLineByLine('13.main.txt'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment