|
| 1 | +// TODO:: refactor |
| 2 | + |
| 3 | +import { readFile } from 'node:fs/promises'; |
| 4 | +import { resolve } from 'node:path'; |
| 5 | + |
| 6 | +async function main() { |
| 7 | + const data = await readFile( |
| 8 | + resolve('../../../../', 'data', '2024-05.txt'), |
| 9 | + 'utf8' |
| 10 | + ); |
| 11 | + |
| 12 | + // Part 1 |
| 13 | + { |
| 14 | + console.time('Part 1'); |
| 15 | + const result = part1(data); |
| 16 | + console.info('Result:', result); |
| 17 | + console.timeEnd('Part 1'); |
| 18 | + } |
| 19 | + |
| 20 | + // Part 2 |
| 21 | + { |
| 22 | + console.time('Part 2'); |
| 23 | + const result = part2(data); |
| 24 | + console.info('Result:', result); |
| 25 | + console.timeEnd('Part 2'); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +main(); |
| 30 | + |
| 31 | +export function part1(data: string) { |
| 32 | + const lines = data.trim().split('\n'); |
| 33 | + const pages = lines.slice(0, lines.indexOf('')); |
| 34 | + const updates = lines |
| 35 | + .slice(lines.indexOf('') + 1) |
| 36 | + .map((i) => i.split(',').map(Number)); |
| 37 | + |
| 38 | + let sum = 0; |
| 39 | + |
| 40 | + for (let i = 0; i < updates.length; i++) { |
| 41 | + const update = updates[i]; |
| 42 | + let safe = false; |
| 43 | + |
| 44 | + outerLoop: for (let j = 0; j < update.length; j++) { |
| 45 | + for (let k = j + 1; k < update.length; k++) { |
| 46 | + const str = `${update[j]}|${update[k]}`; |
| 47 | + if (!pages.includes(str)) { |
| 48 | + safe = false; |
| 49 | + break outerLoop; |
| 50 | + } |
| 51 | + safe = true; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + if (safe) { |
| 56 | + sum += update[Math.floor(update.length / 2)]; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return sum; |
| 61 | +} |
| 62 | + |
| 63 | +export function part2(data: string) { |
| 64 | + const lines = data.trim().split('\n'); |
| 65 | + const pages = lines.slice(0, lines.indexOf('')); |
| 66 | + const updates = lines |
| 67 | + .slice(lines.indexOf('') + 1) |
| 68 | + .map((i) => i.split(',').map(Number)); |
| 69 | + |
| 70 | + let sum = 0; |
| 71 | + |
| 72 | + for (let i = 0; i < updates.length; i++) { |
| 73 | + const update = updates[i]; |
| 74 | + let safe = false; |
| 75 | + |
| 76 | + outerLoop: for (let j = 0; j < update.length; j++) { |
| 77 | + for (let k = j + 1; k < update.length; k++) { |
| 78 | + const str = `${update[j]}|${update[k]}`; |
| 79 | + if (!pages.includes(str)) { |
| 80 | + if (pages.includes(`${update[k]}|${update[j]}`)) { |
| 81 | + [update[j], update[k]] = [update[k], update[j]]; |
| 82 | + safe = true; |
| 83 | + // continue outerLoop; |
| 84 | + } else { |
| 85 | + safe = false; |
| 86 | + break outerLoop; |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + if (safe) { |
| 93 | + sum += update[Math.floor(update.length / 2)]; |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + return sum; |
| 98 | +} |
0 commit comments