DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 4: Secure Container

Collapse
 
supriyasrivatsa profile image
Supriya Srivatsa • Edited

Kotlin code, used groupBy for the double digit condition checks - github.com/sup95/AdventOfCode-19/b... :)

fun main() {
    var part1Result = 0
    var part2Result = 0

    for(i in 357253..892942) {
        val numAsCharArray = i.toString().map { it }
        if (isDigitsNonDecreasing(numAsCharArray)) {
            if(hasAtleastDouble(numAsCharArray)) part1Result++
            if(hasExactlyDouble(numAsCharArray)) part2Result++
        }
    }

    println(part1Result)    //530
    println(part2Result)    //324
}

fun hasAtleastDouble(numAsChar: List<Char>) : Boolean {
    return numAsChar.groupBy { it }.filter { it.value.size >= 2 }.isNotEmpty()
}

fun hasExactlyDouble(numAsChar: List<Char>) : Boolean {
    return numAsChar.groupBy { it }.filter { it.value.size == 2 }.isNotEmpty()
}

fun isDigitsNonDecreasing(numAsChar: List<Char>) : Boolean {
    return numAsChar == numAsChar.sorted()
}
Collapse
 
jbristow profile image
Jon Bristow

Unsolicited code review:

filter(x).isEmpty() is equivalent to none(x)

filter(x).isNotEmpty() is equivalent to any(x)

filterNot(x).isEmpty() is equivalent to all(x)

filterNot(x).isNotEmpty() is equivalent to any(!x)

c.any{it == x} is equivalent to x in c

I find future me tends to remember what I was doing faster when I use the any/none/all functions. (They also short-circuit, but the readability boost to my productivity helps more than the loop optimization)