summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoreug-vs <eugene@eug-vs.xyz>2023-12-05 23:35:39 +0300
committereug-vs <eugene@eug-vs.xyz>2023-12-05 23:35:39 +0300
commit50848c9299ededef12261011eaca60037aabcb42 (patch)
tree66fca861f6e28c783246620b923a49ee79f8cc61
parent7991dc2e29c4ee94de9d07b898fbe4c3130784bc (diff)
downloadaoc-2023-50848c9299ededef12261011eaca60037aabcb42.tar.gz
feat(day-5): add part 2 solution
-rw-r--r--day-5/script.ts29
1 files changed, 27 insertions, 2 deletions
diff --git a/day-5/script.ts b/day-5/script.ts
index 2d18477..f0eb76e 100644
--- a/day-5/script.ts
+++ b/day-5/script.ts
@@ -3,8 +3,20 @@ import fs from "fs";
const input = fs.readFileSync("./input.txt").toString();
const [seedStr, ...mapStrings] = input.split("\n\n");
-
-const seeds = seedStr.match(/\d+/g)?.map(Number) || [];
+export function chunks<T>(data: Array<T>, chunkSize: number) {
+ return data.reduce((acc, value, index) => {
+ // Initialize a new chunk
+ if (index % chunkSize === 0) acc.push([]);
+ acc[acc.length - 1].push(value);
+ return acc;
+ }, [] as T[][]);
+}
+
+const seedRanges = chunks(seedStr.match(/\d+/g)?.map(Number) || [], 2).map(
+ ([start, size]) => {
+ return { start, size };
+ },
+);
const maps = mapStrings.map((mapString) =>
mapString
@@ -19,6 +31,19 @@ const maps = mapStrings.map((mapString) =>
})),
);
+// We dont need to inspect whole seed ranges, instead we only select "interesting points"
+// Interesting points lie at starts/end of ranges defined in our maps
+const seeds = maps
+ .flatMap((ranges) =>
+ ranges.flatMap((r) => [r.sourceStart, r.destinationStart + 1]),
+ )
+ .filter((breakpoint) =>
+ seedRanges.find(
+ (range) =>
+ breakpoint >= range.start && breakpoint < range.start + range.size,
+ ),
+ );
+
const locationNumbers = seeds.map((seed) =>
maps.reduce((currentNumber, mapRules) => {
const validRule = mapRules.find(