<Advent of Code 2025 day 3> (spoilers) :thread:
# advent-of-code
a
d
Easiest one so far 🙂
K 1
Screenshot 2025-12-02 at 9.14.57 PM.png
m
Part 1
Part 2
@Dan Fingal-Surma Nice, I like your approach better than mine haha
🙂 1
n
Nice and quick. Night and day from Day 2.
y
@Dan Fingal-Surma imo day 2 was easier if you solved with brute-force. This one is also very easy though.
b
this one i found easier than 1 and 2
if i didn't start late it would probably be a record time for me
a little recursion
K 1
n
9ms cold; 547us warm
@bj0 Très élégant. I like how you use the withIndex() to one-pass the search for the highest value without resorting to the imperative code that I did. Though at least I can exit early when I hit my first '9'!
🙌 1
y
I think advent of code is the only time when I use tail recursion. https://github.com/y9san9/aoc25/blob/main/day3.part2.main.kts
K 1
p
It fees like difficulty is decreasing from 1-3 to me K
a
My day 3 solution. Finally, had a chance to use
tailrec
in prod 😝
Copy code
class Day03(input: String) {

    private val banks = input.lines()

    fun solvePart1() = banks.sumOf {
        findMaxJoltage(it, 2).toInt()
    }

    fun solvePart2() = banks.sumOf {
        findMaxJoltage(it, 12).toLong()
    }

    tailrec fun findMaxJoltage(bank: String, count: Int, acc: String = ""): String =
        if (count == 1) {
            acc + bank.max()
        } else {
            val window = bank.dropLast(count - 1)
            val maxDigit = window.withIndex().maxBy { it.value }
            findMaxJoltage(bank.drop(maxDigit.index + 1), count - 1, acc + maxDigit.value)
        }
}
e
greedy non-recursion
a
@y9san9 is it possible to define your
data class Joltage
actually as
value class
?
y
@Andriy yes it is, but I am sick of @JvmInline that should be then removed everywhere once the feature is released, so I create data classes until we have value classes without @JvmInline
e
it also would make little difference here since it ends up being boxed in List
p
Simple loop for me today.
d
@y9san9 I needed that
O(sqrt(n))
time on problem 2 though 😂
❤️ 1
a
today's was easier but my 💡 moment was "find the max while leaving enough for the remaining digits." after that, the approach seems to be similar with different implementations
k
Complexity: O(N) --------------------- Part 1: duration = 618.3us Part 2: duration = 1.215200ms
Copy code
fun findMaxVoltageForBank(bank: String, target: Int): Long {
    val bankLength = bank.length
    val stack = mutableListOf<Char>()
    bank.forEachIndexed { i, c ->
        while (stack.isNotEmpty() && c > stack.last() && (stack.lastIndex + bankLength - i) >= target) stack.removeLast()
        if (stack.size < target) stack.add(c)
    }
    return stack.joinToString("").toLong()
}
https://github.com/karloti/aoc-2025-in-kotlin/blob/main/src/Day03.kt
m
Interesting challenge, solvable without optimisation but of course much faster when remembering the optimal result during the recursion.
Copy code
fun main() {
    val banks = generateSequence(::readLine).map { it.map(Char::digitToInt) }.toList()

    fun List<Int>.solve(n: Int): Long {
        var solution = listOf<Int>()

        fun List<Int>.pick(n: Int, pos: Int = 0, picked: List<Int> = listOf()): List<Int>? {
            if (n == 0) return picked

            val candidates = pos..indices.last - (n - 1)
            val max = candidates.maxOf { this[it] }

            if (picked.size in solution.indices && solution[picked.size] >= max) return null

            return candidates
                .filter { this[it] == max }
                .mapNotNull { pick(n - 1, it + 1, picked + max) }
                .maxByOrNull { it.joinToString("").toLong() }
                ?.also { solution = it }
        }
        pick(n)

        return solution.joinToString("").toLong()
    }

    listOf(2, 12).map { n -> banks.sumOf { it.solve(n) } }.forEach(::println)
}
^ Hopelessly over-engineered - what was I thinking? Never work on AoC without your morning coffee 😉
➕ 2
k
For part2, i maintained a sorted list, as we only have limited digits.. Maintaining a list can be slow.. but it took 8ms to get the correct result on my machine.
m
My 6am morning brain didn't like that one. I went with memoization for some reason. Still suspiciously slow (130ms). But result is correct so I don't care 😅
k
Part 1 was a breeze. But part 2 needed a bit more thought. Not super optimized, but it gets the job done. Unified solution: https://github.com/kingsleyadio/adventofcode/blob/main/src/com/kingsleyadio/adventofcode/y2025/Day03.kt
m
Unified solution for both parts using a Stack. Complexity is O(N).
j
I’m not crazy about my solution, but I like my new
cached
(one argument) and
cached2
(two arguments) memoization helper functions:
Copy code
data class Bank(val digits: List<Int>) {
        constructor(s: String) : this(s.toCharArray().map { it.digitToInt() })
        fun maxOutput(outputSize: Int): Long = maxOutput(outputSize, digits.size)
        val maxOutput = cached2 { outputSize: Int, inputSize: Int ->
            when {
                outputSize > inputSize -> -1L
                outputSize == 0 -> 0L
                else -> (0..<inputSize).maxOf { idx -> this(outputSize-1, idx)*10 + digits[idx] }
            }
        }
    }
nice spin 2
t
This was also pretty fun, I used
List<List<Int>>
for reading from file (just like as right before me @Jaap Beetstra as I guess) and it's pretty effective (3.06ms for 12 digits and 2.42 for 2)
Copy code
fun firstMaxJoltageN(bank: List<Int>, start: Int = 0, end: Int = 0): Int {
    var index = start
    for (i in start..<bank.size - end) {
        if (bank[i] > bank[index]) {
            index = i
            if (bank[i] == 9) {
                break
            }
        }
    }
    return index
}

fun determineMaxJoltageN(bank: List<Int>, n: Int): Long {
    var maxJoltage = 0L
    var id = 0
    for (i in 0 until n) {
        val index = firstMaxJoltageN(bank, id, n - i - 1)
        maxJoltage = maxJoltage * 10 + bank[index]
        id = index + 1
    }
    return maxJoltage
}
p
I think I prefer the tailrec solution, but there's something nice about avoiding all string manipulations, not that it seems to make a huge difference in performance.
Copy code
year 2025 day 3 part 1
	 Scanning took 26.501us 👑: 17142
	 Tailrec took 30.153us (1.14x): 17142
	 Default took 39.516us (1.49x): 17142
year 2025 day 3 part 2
	 Scanning took 49.278us 👑: 169935154100102
	 Tailrec took 77.457us (1.57x): 169935154100102
	 Default took 89.909us (1.82x): 169935154100102
n
but I like my new
cached
(one argument) and
cached2
(two arguments) memoization helper functions
@Jaap Beetstra where is the hashmap stored? A few years back someone had a memo helper that used a CacheSupport Object that used some fancy casting to provide hashmap services on demand. I asked for permission to use it but then never did because it was slower than rolling my own, perhaps because it used a ConcurrentHashMap.
j
Some room for improvement, but I did a visualization thingy. https://github.com/JBeet/MyAdventOfCode/blob/main/src/aoc2025/Day03_visual.kt
🙌 2
@Neil Banman it uses a basic mutable map, with an
invoke
operator. You can check my GitHub but the main logic is:
Copy code
fun <K1, K2, V> cached2(block2: Cache2<K1, K2, V>.(K1, K2) -> V) = Cache2(block2)
  
  abstract class Cache<K, V>(val items: MutableMap<K, V> = mutableMapOf()) {
      operator fun get(key: K): V = items.getOrPut(key) { calculate(key) }
      abstract fun calculate(key: K): V
  }
  class Cache2<K1, K2, V>(private val calculate2: Cache2<K1, K2, V>.(K1, K2) -> V) : Cache<Pair<K1, K2>, V>() {
      operator fun invoke(key1: K1, key2: K2): V = get(key1 to key2)
      override fun calculate(key: Pair<K1, K2>): V = calculate2(key.first, key.second)
  }
n
Aha, that makes sense! I've always been hazy on the invoke operator. This was a good spark to learn a little more about it.
112 Views