• Zorothamya [she/her, he/him]
    ·
    edit-2
    1 day ago

    This is my kotlin script for part 2

    import java.io.File
    import kotlin.math.abs
    
    fun safeP(increasing: Boolean, pair: Pair<Int, Int>): Boolean =
        (abs(pair.second - pair.first) in 1..3) && (increasing == pair.second - pair.first > 0)
    
    val lines: List<String> = File("day02-input").readLines().map { it.trim() }.filterNot { it == "" }
    val sequences: List<List<Int>> = lines.map { it.split(" ").map { it.toInt() } }
    
    fun getProgressions(seq: List<Int>) =
        generateSequence(-1) { if (it + 1 != seq.size) it + 1 else null }
            .map { progVariation: Int ->
                seq.filterIndexed { index, _ -> index != progVariation }
                    .let { alternateSeq: List<Int> ->
                        alternateSeq.mapIndexed { i: Int, level: Int ->
                            if (i != alternateSeq.lastIndex) level to alternateSeq[i + 1] else null
                        }
                    }
                    .filterNotNull()
            }
    
    val answer = sequences.count { sequence: List<Int> ->
        getProgressions(sequence).any { prog: List<Pair<Int, Int>> ->
            prog.all { safeP(true, it) } || prog.all { safeP(false, it) }
        }
    }
    
    println(answer)
    

    I'm still only learning kotlin. In my opinion it's pretty shitty code due to the long call chains. I imagine to make it better I should probably break up those chains, assigining the intermediate values to different variables, to make it more readable. Do you agree and is there other stuff that you think ought to be improved?

    • zongor [comrade/them, he/him]
      hexagon
      ·
      12 hours ago

      Prefix with I don't know much about Kotlin except that its a JVM language. It looks like you are programming in a functional style more than a OOP or imperative style. So in an imperative style you would have more intermediate values, but in a function style you are trying to reduce unnecessary intermediate values and have the output of one function pipe into the next function in the chain.