From e70b4189cf0e4dcc18225992d4cc7e2f3aa6b6b0 Mon Sep 17 00:00:00 2001 From: monoid Date: Wed, 11 Dec 2024 14:41:44 +0900 Subject: [PATCH] Add solution day 11 --- day_11/input.txt | 1 + day_11/solve_1.ts | 31 +++++++++++++++++++++++++++++++ day_11/solve_2.ts | 30 ++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 day_11/input.txt create mode 100644 day_11/solve_1.ts create mode 100644 day_11/solve_2.ts diff --git a/day_11/input.txt b/day_11/input.txt new file mode 100644 index 0000000..f89b9fd --- /dev/null +++ b/day_11/input.txt @@ -0,0 +1 @@ +6 11 33023 4134 564 0 8922422 688775 \ No newline at end of file diff --git a/day_11/solve_1.ts b/day_11/solve_1.ts new file mode 100644 index 0000000..aa8bfaa --- /dev/null +++ b/day_11/solve_1.ts @@ -0,0 +1,31 @@ +export async function readInputData(path: string): Promise { + const data = await Deno.readTextFile(path); + return data.trim().split(" ").map((x) => parseInt(x)); +} + +export function step(k: number): [number, number] | number { + if (k === 0) return 1; + const str = k.toString(); + if (str.length % 2 === 0) { + return [ + parseInt(str.slice(0, str.length / 2)), + parseInt(str.slice(str.length / 2)), + ]; + } + return k * 2024; +} + +if (import.meta.main) { + const input = await readInputData("input.txt"); + console.log(input); + let data = input; + for (let i = 0; i < 25; i++) { + data = data.flatMap(step); + } + console.log(data.length); + // let input = [125, 17] + // for (let i = 0; i < 6; i++) { + // input = input.flatMap(step); + // console.log(input); + // } +} diff --git a/day_11/solve_2.ts b/day_11/solve_2.ts new file mode 100644 index 0000000..451b440 --- /dev/null +++ b/day_11/solve_2.ts @@ -0,0 +1,30 @@ +import { readInputData, step as stepNext } from "./solve_1.ts"; + +let memo: Map = new Map(); +function countStone(start: number, step: number): number { + if (step === 0) return 1; + const key = `${start},${step}`; + const memoized = memo.get(key); + if (memoized) return memoized; + const next = stepNext(start); + if (typeof next === "number") { + const count = countStone(next, step - 1); + memo.set(key, count); + return count; + } + const [a, b] = next; + const count = countStone(a, step - 1) + countStone(b, step - 1); + memo.set(key, count); + return count; +} + +if (import.meta.main) { + const input = await readInputData("input.txt"); + const data = input; + console.log(data.reduce((a, b) => a + countStone(b, 75), 0)); + // let input = [125, 17] + // for (let i = 0; i < 6; i++) { + // input = input.flatMap(step); + // console.log(input); + // } +}