From dad2acc413a5e2f72ec655eb6bd8e136f2187690 Mon Sep 17 00:00:00 2001 From: Seth Etter Date: Tue, 5 Dec 2023 20:53:39 -0600 Subject: [PATCH] split up seed ranges into promises, it worked! --- 2023/day05/part2.ts | 36 +++++++++++++++++++++++------------- 2023/day05/test.ts | 4 ++-- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/2023/day05/part2.ts b/2023/day05/part2.ts index 0ed8493..1975b49 100644 --- a/2023/day05/part2.ts +++ b/2023/day05/part2.ts @@ -6,7 +6,7 @@ if (import.meta.main) { new TextDecoder().decode(bytes), ) ).trim(); - console.log(answer(input)); + console.log(await answer(input)); } type Range = { @@ -21,9 +21,9 @@ type MapRanges = { ranges: Range[]; }; -export function answer(input: string): number { +export async function answer(input: string): Promise { const [seedLine, _, ...mapLines] = input.split("\n"); - const seedRanges = seedLine + const seedRangeLines = seedLine .replace("seeds: ", "") .split(" ") .map((x) => parseInt(x)); @@ -44,18 +44,28 @@ export function answer(input: string): number { return { from, to, ranges }; }); - let minLocNum = Infinity; - for (let i = 0; i < seedRanges.length; i += 2) { - const from = seedRanges[i]; - const to = from + seedRanges[i + 1]; - for (let j = 0; j < to - from; j++) { - const seed = seedRanges[i] + j; - const locNum = getLocationNumber(seed, mapRanges); - if (locNum < minLocNum) minLocNum = locNum; - } + const seedRanges: [number, number][] = []; + for (let i = 0; i < seedRangeLines.length; i += 2) { + const from = seedRangeLines[i]; + const to = from + seedRangeLines[i + 1]; + seedRanges.push([from, to]); } + const rangeMins = await Promise.all( + seedRanges.map( + ([from, to]) => + new Promise((resolve) => { + let minLocNum = Infinity; + for (let j = 0; j < to - from; j++) { + const seed = from + j; + const locNum = getLocationNumber(seed, mapRanges); + if (locNum < minLocNum) minLocNum = locNum; + } + return resolve(minLocNum); + }), + ), + ); - return minLocNum; + return Math.min(...rangeMins); } function getLocationNumber(seed: number, mapRanges: MapRanges[]): number { diff --git a/2023/day05/test.ts b/2023/day05/test.ts index f2962d3..8b123db 100644 --- a/2023/day05/test.ts +++ b/2023/day05/test.ts @@ -42,7 +42,7 @@ Deno.test("part1", () => { assertEquals(p1.answer(examples), 35); }); -Deno.test("part2", () => { +Deno.test("part2", async () => { const examples = [ "seeds: 79 14 55 13", "", @@ -79,5 +79,5 @@ Deno.test("part2", () => { "60 56 37", "56 93 4", ].join("\n"); - assertEquals(p2.answer(examples), 46); + assertEquals(await p2.answer(examples), 46); }); -- 2.51.2