DEV Community

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

Collapse
 
jbristow profile image
Jon Bristow • Edited

Kotlin Solution

object Day04 {

    private fun has5DistinctNumbers(it: Int) = it.toString().toSet().size < 6

    private fun hasAllIncreasingDigits(it: Int) =
        it.toString()
            .map { it.toInt() }
            .windowed(2, 1)
            .all { (a, b) -> b >= a }

    private fun hasAtLeastOneDigitAppearingExactlyTwice(it: Int) =
        it.toString()
            .groupBy { it }
            .mapValues { (k, v) -> v.size }
            .any { (k, v) -> v == 2 }

    fun part1() =
        passwordRange.asSequence()
            .filter { hasAllIncreasingDigits(it) && has5DistinctNumbers(it) }
            .count()

    fun part2() =
        passwordRange.asSequence()
            .filter { hasAllIncreasingDigits(it) && hasAtLeastOneDigitAppearingExactlyTwice(it) }
            .count()

}

fun main() {
    println(Day04.part1())
    println(Day04.part2())
}

It's important to use Sequence here so that the map/filter/count function can happen per item instead of applying to the whole list for each operation.

Collapse
 
farahanjum profile image
Farah Anjum

Something about seeing so many greens <3
Waiting for someone to post a functional/not-very-imperative JS solution!

Collapse
 
farahanjum profile image
Farah Anjum

Where in part1() are you checking that 2 adjacent digits are the same?

Collapse
 
jbristow profile image
Jon Bristow • Edited

Here’s my math/logic for n=3 that expands to a general case simply in my mind (if it doesn’t I can work on a more formal proof)

Given:

  • a<=b<=c
  • a==b OR b==c

Therefore:

  • distinct(a,b,c) must be equal to (a,c) OR (a)
  • aba is never a legal pattern

Explanation of the second therefore: By looking at a 4 digit number that is abca we see that since this implies c<=a<=b that this isn’t a legal string. We can also insert any number of digits (that follow the rules) between b and c and the contradiction with given #1 still occurs.