Day 4: <https://github.com/tginsberg/advent-2019-k...
# advent-of-code
Mine probably isn't super efficient, I go over the candidates a few times. But I'm aiming for clarity so I'm happy with it.
k
oooh, zipWithNext. I used
v.zip(v.drop(1))
t
It's amazing what's in the Kotlin Standard Library, isn't it?
b
I guess I will have to try to use a more functional approach for the next days. Your solution is so much more elegant than my simple for loop 😉. However I only loop over each number once and not twice.
Also
containsMatchingPair(it) && containsIsolatedPair(it)
is a bit overkill since
containsIsolatedPair(it)
already implies
containsMatchingPair(it)
k
technically it doesn't.
isSorted && containsIsolatedPair -> containsMatchingPair
though
b
yeah your right
t
Yeah, mine is probably not as efficient as it could be. But my goal is to a) Solve the AoC problem and not the general case of problems like that and b) Explain it to people (I blog about each day, which I'll write later after work). So my code almost always sacrifices speed for explainability. 🙂
👍 1
b
Totally agree with those goals. That said
isSorted(it) && containsMatchingPair(it) && containsIsolatedPair(it)
looks like those a 3 separate conditions, while in fact they are only 2.
t
Yeah, that's true. I'll fix that. 🙂
j
Ah damn, I thought I couldn't use
groupBy
but I now realize you can, as a side-effect of also checking that the numbers are ever-increasing! Clever stuff
Not realizing this made my solution ugly:
Copy code
fun Int.groupedDigits(): List<List<Char>> {
  val result = mutableListOf(mutableListOf<Char>())
  this.toString().forEach {
    if (result.last().contains(it)) {
      result.last().add(it)
    } else {
      result.add(mutableListOf(it))
    }
  }
  return result.drop(1)
}

fun Int.isValidPassword2(): Boolean {
  val groups = this.groupedDigits()
  val hasIsolatedPair = groups.any { it.size == 2 }
  val everIncreasing = groups.windowed(2).all { 
    it[0].first() < it[1].first()
  }
  return hasIsolatedPair && everIncreasing
}
e
Interestingly, I made a function similar to @Joris PZ’s and was surprised to find that it performs a couple of ms better than
groupBy { it }.any { it.value.size == 2 }
.
k
I was about to make the same comments about
groupBy
not working as @Joris PZ, pretty clever.
Assuming you actually thought about it of course 😉