• 16 Posts
  • 351 Comments
Joined 3 years ago
cake
Cake day: June 17th, 2023

help-circle

  • Kotlin

    I reached my solution with no aoc spoilers, after some research I figured out, that there really is no easy solution to this “packing problem”. So with a sigh, I wrote a brute-force approach which tries every shape in every possible orientation, with a simple check if they could even fit at all first. To make it a little fun, I decided to implement my own matrix rotation function. I made it generic and prettier a few days later, but this code still uses the old one, due to it specifically using a BooleanArray for a (hopefully) smaller memory / performance footprint. As all shapes are 3x3, the brute-force algorithm works by placing the center position everywhere except for the outer edges of the available space.

    Now that I have read the answers here, I feel stupid… But unlike all of your solutions here, mine do indeed work on the example and real input, so take that I guess. In hindsight, I should have been a lot more suspicious of how this is able to run in under 10 seconds, but oh well.

    Obviously very bloated code due to it technically working on non trivial cases:

    Solution
    private fun rotate3by3(grid: Array<BooleanArray>, k: Int) {
        if (k % 4 == 0) return
        val indices = listOf(
            0 to 0,
            0 to 1,
            0 to 2,
            1 to 2,
            2 to 2,
            2 to 1,
            2 to 0,
            1 to 0,
        )
        val ring = indices.map { (x, y) -> grid[x][y] }.toMutableList()
        Collections.rotate(ring, 2 * (k % 4))
        indices.forEachIndexed { index, (x, y) -> grid[x][y] = ring[index] }
    }
    
    class Day12 : Puzzle {
    
        lateinit var shapes: List<Shape>
        lateinit var areas: List<Area>
    
        private val points3by3 = listOf(
            -1 to -1,
            -1 to 0,
            -1 to 1,
            0 to -1,
            0 to 0,
            0 to 1,
            1 to -1,
            1 to 0,
            1 to 1,
        )
    
        override fun readFile() {
            val input = readInputFromFile(2025, 12, false)
            val split = input.trim().split("\n\n")
    
            val shapeList = mutableListOf<Shape>()
            for (shape in split.take(split.size - 1)) {
                shapeList.add(Shape(shape))
            }
            shapes = shapeList
    
            areas = split.last().lines().map { Area(it) }
        }
    
        override fun solvePartOne(): String {
            var sum = 0L
            for (area in areas) {
                val shapesToFit = area.idCount.asSequence()
                    .filter { it.value > 0 }
                    .flatMap { entry -> List(entry.value) { shapes[entry.key] } }
                    .sortedByDescending { it.size }
    
                // trivial case
                if (shapesToFit.sumOf { it.size } > area.size) continue
    
                sum += if (pack(FilledArea(area), shapesToFit)) 1L else 0L
            }
            return sum.toString()
        }
    
        private fun pack(filledArea: FilledArea, shapes: Sequence<Shape>): Boolean {
            val next = shapes.firstOrNull() ?: return true
    
            for (state in next.states()) {
                for (centerPos in filledArea.fits(state)) {
                    if (pack(filledArea.newAreaWithShape(centerPos, state), shapes.drop(1))) return true
                }
            }
    
            return false
        }
    
        override fun solvePartTwo(): String {
            return "Not implemented"
        }
    
        data class Shape(val inputString: String) {
            val index: Int = inputString.lines()[0].replace(":", "").toInt()
            val grid: Array<BooleanArray>
    
            val size
                get() = grid.sumOf { row -> row.count { it } }
    
            init {
                val tempGrid = mutableListOf<BooleanArray>()
                for ((i, line) in inputString.lines().withIndex()) {
                    if (i == 0) continue // skip index
                    val list = mutableListOf<Boolean>()
                    for (char in line) {
                        when (char) {
                            '#' -> list.add(true)
                            '.' -> list.add(false)
                            else -> throw Exception("Malformed input line: $line")
                        }
                    }
                    tempGrid.add(list.toBooleanArray())
                }
                grid = tempGrid.toTypedArray()
            }
    
            // generate all rotations + flips
            fun states(): List<Array<BooleanArray>> {
                val out = mutableListOf<Array<BooleanArray>>()
                val flips = mutableListOf(
                    grid.map { it.copyOf() }.toTypedArray(), // normal
                    grid.map { it.copyOf() }.reversed().toTypedArray(), // horizontal
                    grid.map { it.copyOf().reversed().toBooleanArray() }.toTypedArray(), // vertical
                    grid.map { it.copyOf().reversed().toBooleanArray() }.reversed().toTypedArray(), // both
                )
    
                for (flip in flips) {
                    for (k in 0..3) {
                        val arr = flip.map { it.copyOf() }.toTypedArray()
                        rotate3by3(arr, k)
                        out.add(arr)
                    }
                }
    
                return out.distinctBy { it.contentDeepHashCode() }
            }
        }
    
        data class Area(val inputString: String) {
            val width: Int
            val height: Int
            val idCount: Map<Int, Int> // <index, count>
    
            val size
                get() = width * height
    
            init {
                val split = inputString.split(": ")
                val sizeSplit = split[0].split("x")
                width = sizeSplit[0].toInt()
                height = sizeSplit[1].toInt()
                idCount = split[1].split(" ").mapIndexed { index, s -> index to s.toInt() }
                    .filter { it.second != 0 }
                    .toMap()
            }
        }
    
        inner class FilledArea(
            val width: Int,
            val height: Int,
            val grid: Array<BooleanArray> = Array(height) { BooleanArray(width) { false } },
            ) {
            constructor(area: Area) : this(area.width, area.height)
    
            // 3x3 shape -> position = center point
            // returns every possible center point
            fun fits(shape: Array<BooleanArray>): List<Pair<Int, Int>> {
                val out = mutableListOf<Pair<Int, Int>>()
                // 3x3 centers -> skip edges
                for (r in grid.indices.filter { it != 0 && it != grid.size - 1 }) {
                    for (c in grid[r].indices.filter { it != 0 && it != grid[r].size - 1 }) {
                        val fits = points3by3.count { (dx, dy) ->
                            grid[r + dx][c + dy] && shape[1 + dx][1 + dy]
                        } == 0
                        if (fits) out.add(r to c)
                    }
                }
                return out
            }
    
            // returns a new FilledArea, with the given shape inserted into it
            // no space check !!
            fun newAreaWithShape(centerPos: Pair<Int, Int>, shape: Array<BooleanArray>): FilledArea {
                val newGrid = grid.map { it.copyOf() }.toTypedArray()
                val (cx, cy) = centerPos
                points3by3.forEach { (dx, dy) ->
                    newGrid[cx + dx][cy + dy] = shape[1 + dx][1 + dy]
                }
                return FilledArea(width, height, newGrid)
            }
    
            override fun equals(other: Any?): Boolean {
                if (this === other) return true
                if (javaClass != other?.javaClass) return false
    
                other as FilledArea
    
                if (width != other.width) return false
                if (height != other.height) return false
                if (!grid.contentDeepEquals(other.grid)) return false
    
                return true
            }
    
            override fun hashCode(): Int {
                var result = width
                result = 31 * result + height
                result = 31 * result + grid.contentDeepHashCode()
                return result
            }
        }
    }
    

    full code on Codeberg


  • Kotlin

    Part 1 was very straightforward, just a simple, cached recursive crawler.

    In hindsight, part 2 works great with the same code and a small restriction. This took me quite a few off-by-one errors and Integer overflows to properly code though.

    Solution
    class Day11 : Puzzle {
    
        val links = mutableMapOf<String, List<String>>()
        val input1 = "you"
        val input2 = "svr"
        val output = "out"
    
        val cache = mutableMapOf<Pair<String, Set<Pair<String, Boolean>>>, Long>()
    
        override fun readFile() {
            val input = readInputFromFile(2025, 11, false)
            for (line in input.lines().filter { it.isNotBlank() }) {
                val split = line.split(": ")
                links[split[0]] = split[1].split(" ")
            }
        }
    
        override fun solvePartOne(): String {
            return travel(input1, setOf()).toString()
        }
    
        override fun solvePartTwo(): String {
            val passed = listOf("dac", "fft")
                .map { Pair(it, false) }
                .toSet()
            return travel(input2, passed).toString()
        }
    
        private fun travel(input: String, passed: Set<Pair<String, Boolean>>): Long {
            if (cache.containsKey(Pair(input, passed))) return cache[Pair(input, passed)]!!
            if (input == output) return if (passed.all { it.second }) 1L else 0L
            val newPassed = if (input in passed.map { it.first }) {
                passed.map { if (it.first == input) input to true else it }.toSet()
            } else {
                passed
            }
            val paths = links[input]!!
            val sum = paths.sumOf { travel(it, newPassed) }
            cache[Pair(input, newPassed)] = sum
            return sum
        }
    }
    

    full code on Codeberg


  • Sorry for necroposting, but now that I have solved this problem 11 months later I can finally look at this thread without getting spoilers.

    I was also completely bamboozled by the amount of combinations for part 2, which made brute-forcing it impossible. I totally agree, solving it with a library is just not as fulfilling as fully solving it yourself. For Kotlin, I used the library ojAlgo. From looking at your code, I would say ojAlgo is a decent bit more readable, although it likely does the same thing as your library under the hood.


  • Kotlin

    Day 10, the end of daily solutions for me… This puzzle really broke me, part 1 as well as part 2.

    For part 1, I eventually just tried all options with memoization. Not very pretty, not very fast (between 5 and 10 seconds runtime), but works reliably enough. My new part 2 is likely applicable to part 1 too, but I am just so done with this one.

    Part 2. Wow. After two nights of unsuccessful brute-force, I saw the linear algebra pretty quickly: The matrix of the buttons (A) times a solution vector (x) is equal to the joltage counts (b). At first glance, this is a very simple $Ax = b$ system of linear equations. This got me 30 / 200 machines, with the Kotlin equivalent of numpy (multik). For the rest, I tried optimizing my brute-force approach in combination with a timeout. Any machine which ran into a timeout, I would manually construct the matrix and put it into a matrix calculator. As you may be able to guess, I couldn’t for the life of me figure out how to solve an underdetermined system in code. This matrix calculator approach worked well for simpler cases, but was horribly slow. For more complex cases, I figured out later that I often did not pick the most optimal solution. So I decided to try my hand at it with Python: After some research, I figured out that sympy can indeed solve underdetermined systems the same way my matrix calculator website did! So now I no longer had to manually type the matrix into the website, my Python code would parse the input and show me the vectors. This was still very error-prone though.
    Eventually, I figured out that scipy has a thing called “optimization algorithms”. That led me to a first, very horribly looking Python solution using scipy’s milp. After I grasped the concept a bit better, I made a much cleaner Python solution with linprog.
    Now that I understood the problem, I wanted to make it work in Kotlin. If you looked at my repo in the past, you will notice that none of my solutions use any external libraries. I really wanted to stick to this, but at the end this problem had been killing me for a week and I just wanted it to be done. ojAlgo to the rescue! With this wonderful java library, my part 2 is very concise and readable, while also being pretty fast.

    Sorry for the part 2 rambling, here’s the solution:

    Solution
    class Day10 : Puzzle {
    
        lateinit var machines: List<Machine>
    
        override fun readFile() {
            val input = readInputFromFile(2025, 10, false)
            machines = input.lines().filter { it.isNotBlank() }.map { Machine(it) }
        }
    
        private fun buildMatrix(machine: Machine) = machine.buttons.map { List(machine.lights.size) { i -> i in it } }
    
        override fun solvePartOne(): String {
            var sum = 0L
            for (machine in machines) {
                val matrix = buildMatrix(machine)
                val iterationLimit = machine.buttons.size
                val cache = mutableMapOf<Triple<List<Boolean>, List<Boolean>, Int>, Long>()
    
                fun traverseRow(row: List<Boolean>, lights: List<Boolean>, presses: Int = 0): Long {
                    val key = Triple(row, lights, presses)
                    if (key in cache) {
                        return cache[key]!!
                    } else if (row == lights) {
                        return 1L
                    } else if (presses == iterationLimit) {
                        return Long.MAX_VALUE
                    } else if (lights.indices.filter { lights[it] }.none { row[it] }) {
                        return Long.MAX_VALUE
                    } else {
                        val newLights = lights.zip(row) { a, b -> a xor b }
                        val min = matrix.filter { it != row }.minOf { traverseRow(it, newLights, presses + 1) }
                        val out = 1L + if (min == Long.MAX_VALUE) Long.MAX_VALUE - 1L else min // careful with MAX + 1
                        cache[key] = out
                        return out
                    }
                }
                sum += matrix.minOf { traverseRow(it, machine.lights) }
            }
            return sum.toString()
        }
    
        override fun solvePartTwo(): String {
            return machines.sumOf(::getMachineSum).toString()
        }
    
        private fun getMachineSum(machine: Machine): Int {
            val buttonMatrix = buildMatrix(machine)        // one row corresponds to one button
            val joltageMatrix = mirrorMatrix(buttonMatrix) // one row corresponds to one joltage counter
                .map { r -> r.map { if (it) 1 else 0 } }
    
            val model = ExpressionsBasedModel()
            val buttons = buttonMatrix.map { row ->
                row.mapIndexedNotNull { i, b -> if (b) i else null }.minOf { machine.joltages[it] }
            }.mapIndexed { i, button ->
                model.newIntegerVariable("button$i").lower(0).upper(button)
            }
    
            // minimize sum over all buttons
            buttons.forEach { model.objective.set(it, 1) }
    
            // joltageMatrix @ buttons = machine.joltages
            for (r in joltageMatrix.indices) {
                val row = model.newConstraint("row$r").level(machine.joltages[r])
                joltageMatrix[r].forEachIndexed { i, j -> row.set(buttons[i], j) }
            }
    
            model.minimise()
            return buttons.sumOf { it.intValue() }
        }
    
        data class Machine(val inputString: String) {
            val lights: List<Boolean>
            val buttons: List<List<Int>>
            val joltages: List<Int>
    
            init {
                val input = inputString.split("] ").flatMap { it.split(" {") }
                lights = input[0].filter { it != '[' }.map { it == '#' }
                buttons = input[1].split(" ").map { listStr ->
                    listStr.filter { it != '(' && it != ')' }.split(",").map { it.toInt() }
                }
                joltages = input[2].filter { it != '}' }.split(",").map { it.toInt() }
            }
        }
    }
    

    full code on Codeberg


  • Kotlin

    Part 1 was pretty straightforward, just compute all sizes and take the maximum.

    Part 2 here was the first puzzle which I couldn’t solve on the day it came out. It took me incredibly long to find a heuristic which works without building the entire filled out grid. Eventually, I realized that you can traverse the edges of a shape, and as long as there is no edge on a neighboring outside cell of your current shape, the shape will be valid.
    My code still builds the edges, as I still had that code and couldn’t be bothered to find an even smarter solution which works based on just start and end points. I’m saving my outline points in a HashSet, with the hope that that’s the fastest data structure for my approach.
    Parallelized for faster runtime, part 2 still takes roughly 2 minutes at 90 % CPU usage for me.

    Solution
    operator fun Point.plus(other: Point): Point {
        return Point(x + other.x, y + other.y)
    }
    
    class Day09 : Puzzle {
    
        lateinit var corners: List<Point>
        lateinit var edges: List<Pair<Point, Point>>
        var firstDeltaX by Delegates.notNull<Boolean>() // whether the first edge is deltaX. If false => first edge is deltaY
    
        override fun readFile() {
            val input = readInputFromFile(2025, 9, false)
            corners = input.lines().filter { it.isNotBlank() }
                .map { it.split(",") }
                .map { Point(it[0].toInt(), it[1].toInt()) }
    
            // In my input, edges always alternate between deltaX and deltaY.
            // Putting the edges into the same list works for me, but may not work for you.
            val mutableEdges = mutableListOf<Pair<Point, Point>>()
    
            for (i in 0..<corners.size - 1) {
                val a = corners[i]
                val b = corners[i + 1]
                if (a.x == b.x) {
                    if (i == 0) firstDeltaX = false
                } else if (a.y == b.y) {
                    if (i == 0) firstDeltaX = true
                } else {
                    println("Error: malformed input for a: $a, b: $b")
                }
                mutableEdges.add(Pair(a, b))
            }
            edges = mutableEdges
        }
    
        override fun solvePartOne(): String {
            return getShapeSizes().max().toString()
        }
    
        override fun solvePartTwo(): String {
            // add missing edge last -> first
            val wrapAroundEdge = Pair(corners.last(), corners.first())
            val newEdges = (edges + listOf(wrapAroundEdge))
    
            // compute the points of all outlines
            val outline = newEdges.asSequence()
                .flatMap { buildEdge(it) }
                .toHashSet()
    
            fun part2ValidityCheck(a: Point, b: Point): Boolean {
                // compute rectangle edges:
                //  --->
                // ^    |
                // |    |
                // |    v
                //  <---
                // 0 -> ; 1 v ; 2 <- ; 3 ^
                val xVals = intArrayOf(a.x, b.x)
                val yVals = intArrayOf(a.y, b.y)
                val rectEdges = listOf(
                    Point(xVals.min(), yVals.min()) to Point(xVals.min(), yVals.max()),
                    Point(xVals.min(), yVals.max()) to Point(xVals.max(), yVals.max()),
                    Point(xVals.max(), yVals.max()) to Point(xVals.max(), yVals.min()),
                    Point(xVals.max(), yVals.min()) to Point(xVals.min(), yVals.min()),
                )
                // walking the edges, how to get to the right point in relation to walking direction
                // (-> inward points)
                val right = arrayOf(
                    Point(1, 0),
                    Point(0, -1),
                    Point(-1, 0),
                    Point(0, 1),
                )
    
                // if we can travel the edges without crossing an edge, the rectangle is valid
                for ((i, testEdge) in rectEdges.withIndex()) {
                    val edge = buildEdge(testEdge)
                    // ignore corners, as they will often have an inward facing edge
                    for (point in edge.slice(1..<edge.size - 1)) {
                        // if the point isn't part of the outline, we're inside the shape
                        // if we're on the outline and there is an inward point,
                        // it means the next rectangle point would go out of bounds
                        // (-> if an edge goes inwards, it eats into our shape)
                        if (outline.contains(point) && outline.contains(point + right[i])) {
                            return false
                        }
                    }
                }
                return true
            }
    
            return getShapeSizes(::part2ValidityCheck).max().toString()
        }
    
        private fun buildEdge(corners: Pair<Point, Point>): List<Point> {
            val deltaX = corners.first.x != corners.second.x
            val range = if (deltaX) {
                IntRange(min(corners.first.x, corners.second.x), max(corners.first.x, corners.second.x))
            } else {
                IntRange(min(corners.first.y, corners.second.y), max(corners.first.y, corners.second.y))
            }
            val out = mutableListOf<Point>()
            for (num in range) {
                if (deltaX) {
                    out.add(Point(num, corners.first.y))
                } else {
                    out.add(Point(corners.first.x, num))
                }
            }
            return out
        }
    
        private fun getShapeSizes(validityCheck: (Point, Point) -> Boolean = { _, _ ->  true }): Set<Long> {
            val set = java.util.concurrent.ConcurrentSkipListSet<Long>()
            val indices = corners.indices.toList()
            indices.parallelStream().forEach { i ->
                for (j in i + 1..<corners.size) {
                    val a = corners[i]
                    val b = corners[j]
                    val area = (abs(a.x - b.x) + 1L) * (abs(a.y - b.y) + 1L)
                    if (area > (set.maxOrNull() ?: 0) && validityCheck(a, b)) set.add(area)
                }
            }
            return set
        }
    }
    

    full code on Codeberg


  • Kotlin

    Looks like I forgot to post my Day 1 solution here last year. Pretty straightforward modulo, could probably be done simpler but this works well:

    Solution
    class Day01 : Puzzle {
    
        val instructions = mutableListOf<Int>()
    
        override fun readFile() {
            val input = readInputFromFile("src/main/resources/a2025/day01.txt")
            instructions.addAll(
                input.lines().filter { it.isNotEmpty() }
                    .map { it.replace('L', '-') }
                    .map { it.replace('R', '+') }
                    .map(String::toInt)
            )
        }
    
        override fun solvePartOne(): String {
            return processInstructions(50, false).toString()
        }
    
        override fun solvePartTwo(): String {
            return processInstructions(50, true).toString()
        }
    
        private fun processInstructions(initialPos: Int, countZeroClicks: Boolean): Int {
            var pos = initialPos
            var zeroPoints = 0
            for (instruction in instructions) {
                val (newPos, zeroClicks) = rotate(pos, instruction)
                pos = newPos
                zeroPoints = if (countZeroClicks) {
                    zeroPoints + zeroClicks
                } else if (pos == 0) {
                    zeroPoints + 1
                } else {
                    zeroPoints
                }
            }
            return zeroPoints
        }
    
        // Pair<newPos, zeroClicks>
        private fun rotate(startPos: Int, steps: Int): Pair<Int, Int> {
            val pos = startPos + steps
            var zeroClicks = pos.absoluteValue / 100
            if (pos < 0 && startPos != 0) zeroClicks++
            if (pos == 0) zeroClicks++
            return Pair(pos.mod(100), zeroClicks)
        }
    }
    

    full code on Codeberg




  • Nope, I was only semi-aware of the forums’ existence. Thanks for the hint, I’ll look into that tomorrow.

    And yes I love my LMS setup too. The software definitely has its odd quirks, but the protocols underneath are just rock solid. I actually own 3 SqueezeBox Radios (one with a battery which lasts many hours!) and a SqueezeBox Touch. I got pretty lucky, all the radios were 20 € used each, and the sb touch a friend had lying around from the time where the Logitech servers were still running.

    Also regarding Airplay, I’ve had a Raspberry Pi + HifiBerry DAC on my AVR for ages. I just wasn’t expecting AirPlay to work well. But it really is insanely good. If you have any device with AirPlay, I sincerely recommend you try connecting it that way and save yourself the hassle of a Raspberry Pi etc.

    Edit:
    Honestly, my motivation for creating another account etc. is very slim. Feel free to share this in whatever way, I don’t mind at all.