Created
December 3, 2023 05:12
-
-
Save bluepichu/a18469aac1b30efc19bf92794968a2e3 to your computer and use it in GitHub Desktop.
aoc23-03.mts
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
import { Advent, f, fm, chr, ord } from "advent"; | |
import { Set, Map } from "immutable"; | |
const { compute, computeCheck } = await Advent({ day: 3 }); | |
compute(2, async (input) => { | |
const data = input.parse(f.cGrid()); | |
let ans = 0; | |
let gearmap = Map<number, Map<number, number[]>>(); | |
for (let i = 0; i < data.length; i++) { | |
let row = data[i]; | |
let ok = false; | |
let val = 0; | |
let gears: [number, number][] = []; | |
for (let j = 0; j < row.length; j++) { | |
// console.log(i, j); | |
if (ord(data[i][j]) >= 0x30 && ord(data[i][j]) <= 0x39) { | |
val *= 10; | |
val += ord(data[i][j]) - 0x30; | |
} else { | |
if (ok) { | |
console.log(val); | |
ans += val; | |
for (let [x, y] of gears) { | |
gearmap = gearmap.update(x, Map<number, number[]>(), (m) => m.update(y, [], (a) => [...a, val])); | |
} | |
ok = false; | |
gears = []; | |
} | |
val = 0; | |
} | |
if (val > 0) { | |
for (let ii = -1; ii <= 1; ii++) { | |
for (let jj = -1; jj <= 1; jj++) { | |
if (ii === 0 && jj === 0) continue; | |
if (i + ii < 0 || i + ii >= data.length) continue; | |
if (j + jj < 0 || j + jj >= row.length) continue; | |
if (data[i + ii][j + jj] !== "." && !(ord(data[i + ii][j + jj]) >= 0x30 && ord(data[i + ii][j + jj]) <= 0x39)) { | |
ok = true; | |
} | |
if (data[i+ii][j+jj] === "*" && !gears.some(([x, y]) => x === i + ii && y === j + jj)) { | |
console.log("gear", i + ii, j + jj); | |
gears.push([i + ii, j + jj]); | |
} | |
} | |
} | |
} | |
// console.log(i, j, val, ok); | |
} | |
if (ok) { | |
ans += val; | |
for (let [x, y] of gears) { | |
gearmap = gearmap.update(x, Map<number, number[]>(), (m) => m.update(y, [], (a) => [...a, val])); | |
} | |
} | |
} | |
// return ans; | |
console.log(gearmap.toJSON()); | |
let ans2 = 0; | |
for (let [_, m] of gearmap) { | |
for (let [_, v] of m) { | |
if (v.length === 2) { | |
ans2 += v[0] * v[1]; | |
} | |
} | |
} | |
return ans2; | |
}); | |
// computeCheck(1, async function* (input) { | |
// const data = input.parse(f.nl(f.int())); | |
// let ans = 0; | |
// yield ans; | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment