AoC-23/Day11/Part1.js

39 lines
994 B
JavaScript
Raw Normal View History

2023-12-12 09:12:20 +00:00
import { readFileSync } from "fs";
const t0 = performance.now();
2023-12-12 09:13:08 +00:00
const input = readFileSync("input.txt")
.toString()
.split(/\r*\n/)
.filter((e) => e.length > 0)
.map((e) => e.split(""));
const expand = (arr) =>
arr.reduce(
(a, i) => [
...a,
...(i.some((e) => e !== ".") ? [i] : [i, Array(i.length).fill(".")]),
],
[]
);
2023-12-12 09:13:38 +00:00
const flip = (current) =>
Array.from({ length: current[0].length }, (_, x) =>
Array.from({ length: current.length }, (_, y) => current[y][x])
);
2023-12-12 09:13:08 +00:00
2023-12-12 09:13:38 +00:00
const universe = flip(expand(flip(expand(input))));
2023-12-12 09:14:25 +00:00
const galaxies = universe
.map((a, y) => a.map((b, x) => ({ s: b, x, y })).filter((b) => b.s === "#"))
.filter((e) => e.length > 0)
.reduce((a, i) => [...a, ...i], []);
2023-12-12 10:05:45 +00:00
const distances = galaxies.map((c, i) =>
galaxies.reduce(
2023-12-15 18:23:01 +00:00
(a, n, j) => a + (j > i ? Math.abs(c.x - n.x) + Math.abs(c.y - n.y) : 0),
2023-12-12 10:05:45 +00:00
0
)
);
const sum = distances.reduce((a, i) => a + i);
console.log(sum);
2023-12-12 09:12:20 +00:00
const t1 = performance.now();
console.log(`Runtime: ${t1 - t0}ms`);