https://kotlinlang.org logo
#advent-of-code
Title
# advent-of-code
b

B Chandrasaimohan

12/09/2023, 10:10 PM
Hi , I am stuck in day9 part1 . My output fails for input . It works for sample input. But for puzzle input it does not work. There are negative values in the input. My code is below. "
Copy code
fun main() {
    val inputList = mutableListOf<String>()
    val inputStream: InputStream = File("day9_23.txt").inputStream()
    inputStream.bufferedReader().useLines { lines ->
        lines.forEach {
            inputList.add(it.toString())
        }
    }

    val rows: List<List<Int>> = inputList.map { it.split(" ").map { i -> i.toInt() } }

   println( rows.sumOf {
         prepareLayers(it)
     } )
}


private fun prepareLayers(row: List<Int>): Int {
    var originalList: MutableList<Int> = row.toMutableList()
    val layeredList: MutableList<MutableList<Int>> = mutableListOf()
    layeredList.add(row.toMutableList())
    do {
        val differences = originalList.windowed(2 ).map { it[1] - it[0] }
        layeredList.add(differences.toMutableList())
        originalList = differences.toMutableList()
    } while (originalList.sum() != 0)
    return layeredList.sumOf { it.last() }
}
My input is : `````` Could you please help me with regards to this
r

Riccardo Lippolis

12/09/2023, 10:37 PM
to check for all zeroes, you're using
sum != 0
, which works for the example because they're all positive numbers, but the actual input has negative numbers (and the sum of a list of positive and negative numbers can be 0, but should not pass this test because they all should be exactly 0)
👍 3
e

Egbor Raphael

12/09/2023, 11:20 PM
Thank you so much i also had that error too
10 Views