Day 4: Perilous Pier

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • eco_game@discuss.tchncs.de
    link
    fedilink
    arrow-up
    4
    ·
    22 hours ago

    Kotlin

    Now that I read the thread, it seems everyone here saw the needed logic quite quickly. I actually started with a brute force approach which solved part 1 decently fast, but for part 2 it couldn’t even crack the example, even with parallelization (those attempts are in my commit history if you’re curious).
    After reapproaching step 2, I realized the problem is actually quite simple, I believe my solution is identical to most ones here.

    One annoying thing, my fit() function is very un-Kotlin-like. If anyone has some cool ideas how to give it more of a Kotlin feel, do let me know because I can’t think of anything.

    Solution
    class Day04 : Puzzle {
    
        private lateinit var barcodes: List<String>
    
        override fun readFile() {
            val input = readInputFromFile(2026, 4, false)
            barcodes = input.lines().filter { it.isNotBlank() }
        }
    
        override fun solvePartOne(): String {
            return barcodes.sumOf { getShortestFit(it) }.toString()
        }
    
        override fun solvePartTwo(): String {
            return getShortestFit(barcodes.joinToString("")).toString()
        }
    
        private fun getShortestFit(barcode: String): Int {
            return barcode.indices.asSequence()
                .map { barcode.substring(0, it + 1) }
                .first { fit(barcode, it.toMutableList()) }
                .length
        }
    
        private fun fit(barcode: String, test: MutableList<Char>): Boolean {
            val offset = test.size
    
            var i = offset
            while (i < barcode.length) {
                for (j in test.indices) {
                    if (i + j >= barcode.length) return true
    
                    val bChar = barcode[i + j]
                    val tChar = test[j]
    
                    when {
                        bChar == tChar || bChar == '?' -> continue
                        tChar != '?' -> return false
                        tChar == '?' -> test[j] = bChar
                        else -> throw IllegalStateException("Encountered unknown characters: barcode='$bChar', test='$tChar'")
                    }
                }
                i += offset
            }
            return true
        }
    }
    

    full code on Codeberg