From 162b48d5cbc58cce208615354c5677b81ba4b827 Mon Sep 17 00:00:00 2001 From: Logiar Date: Wed, 11 Dec 2024 14:44:30 +0100 Subject: [PATCH] In progress day 11 --- day11.kts | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100755 day11.kts diff --git a/day11.kts b/day11.kts new file mode 100755 index 0000000..98278ea --- /dev/null +++ b/day11.kts @@ -0,0 +1,59 @@ +#!/usr/bin/env kotlin +import java.util.Scanner +import java.util.PriorityQueue + + +val scanner = Scanner(System.`in`) + +class PriorityCache(private val maxSize: Int) { + private val cache = mutableMapOf() + private val priorityQueue = PriorityQueue>(compareBy { it.second }) // Pair(Key, Priority) + + fun put(key: K, value: V, priority: Int) { + if (cache.size >= maxSize) { + val leastPriority = priorityQueue.poll() // Remove the lowest-priority item + cache.remove(leastPriority.first) + } + cache[key] = value + priorityQueue.add(Pair(key, priority)) + } + + fun get(key: K): V? { + return cache[key] + } + + fun isCached(key: K): Boolean { + return cache.containsKey(key) + } +} +val priorityCache = PriorityCache(20000) +fun getStonesAfter(input: List,iterations: Int, cache: PriorityCache): Int { + return input.fold(0) { acc, i -> acc + getStoneNumber(i, iterations, cache) } +} +fun getStoneNumber(number: Int, iterations: Int, cache: PriorityCache): Int { + if (iterations == 0) { + return 1 + } else if (cache.isCached("$iterations-$number")) { + return cache.get("$iterations-$number")!! + } else if (number == 0) { + val stonesum = getStonesAfter(listOf(3), iterations - 1, cache) + cache.put("$iterations-0", stonesum, iterations) + return stonesum + } else if (number.toString().length % 2 == 0) { + val mid = number.toString().length / 2 + val left = number.toString().substring(0, mid).toInt() + val right = number.toString().substring(mid).toInt() + val stonesum = getStoneNumber(left, iterations - 1, cache) + getStoneNumber(right, iterations - 1, cache) + cache.put("$iterations-$number", stonesum, iterations) + return stonesum + } else { + val newVal = number * 2024 + val stonesum = getStoneNumber(newVal, iterations - 1, cache) + cache.put("$iterations-$number", stonesum, iterations) + return stonesum + } +} +val input = scanner.nextLine().split(" ").map { it.toInt() } +println("First part with 25 iterations: ${getStonesAfter(input, 25, priorityCache)}") + +