DEV Community

Discussion on: AoC Day 5: Alchemical Reduction

Collapse
 
jbristow profile image
Jon Bristow

Kotlin Solution

A nice easy one! Just fold into a stack and bada-bing-bada-boom!

Part 1

I started with String and String.last. This got me the solution, but it turned out to be really slow. Here's my updated code using a Java LinkedList instead, which is multiple orders of magnitude faster.

fun String.react() =
    fold(LinkedList<Char>()) { acc, c ->
        when {
            acc.isEmpty() -> acc.push(c)
            acc.peek() == c -> acc.push(c)
            acc.peek().equals(c, ignoreCase = true) -> acc.push(c)
            else -> acc.pop()
        }
        acc
    }

fun answer1(input: String) = input.react().count()

Part 2

This one seemed a little too simple at first, but my brute force implementation worked in about a 1500ms (still noticeably slow). After checking that my answer was correct, I did the stack optimization above which pulled me back down to 80ms or so.

fun answer2(input: String) =
    ('a'..'z').zip('A'..'Z')
        .map { (lc, uc) ->
            input.filterNot { it == lc || it == uc }
                .react()
                .count()
        }.min()

Overall, this was a nice mid-week breather, and I'm happy to spend more of my thought cycles doing my OSCP lab work.