Day 6: Trash Compactor

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

  • chunkystyles@sopuli.xyz
    link
    fedilink
    English
    arrow-up
    2
    ·
    4 days ago

    I also thought about trying to rotate, but not for very long. Mine would be a bit simpler if I’d done what you did and build the number string and then check if it’s blank.

    fun main() {
        val input = getInput(6)
        val output = parseInput2(input)
        var total = 0L
        for ((numbers, operator) in output) {
            when (operator) {
                '+' -> { total += numbers.sum() }
                '*' -> { total += numbers.reduce { acc, number -> acc * number }}
            }
        }
        println(getElapsedTime())
        println(total)
    }
    
    fun parseInput2(input: String): List<Pair<List<Long>, Char>> {
        val rows = input.lines()
            .filter { it.isNotBlank() }
            .map { it.toCharArray() }
        val output: MutableList<Pair<List<Long>, Char>> = mutableListOf()
        val numberRowCount = rows.size - 1
        var isNewProblem = true
        var currentNumbers: MutableList<Long> = mutableListOf()
        var operator = ' '
        for (column in rows[0].indices) {
            if (!isNewProblem && isColumnEmpty(rows, column)) {
                isNewProblem = true
                output.add(currentNumbers to operator)
                continue
            }
            if (isNewProblem) {
                isNewProblem = false
                currentNumbers = mutableListOf()
                operator = rows.last()[column]
            }
            var number = ""
            for (row in 0..<numberRowCount) {
                if (rows[row][column] != ' ') {
                    number += rows[row][column]
                }
            }
            currentNumbers.add(number.toLong())
        }
        if (!isNewProblem) {
            output.add(currentNumbers to operator)
        }
        return output
    }
    
    fun isColumnEmpty(rows: List<CharArray>, column: Int): Boolean {
        for (i in rows.indices) {
            if (rows[i][column] != ' ') {
                return false
            }
        }
        return true
    }