Some small improvements to the code (i.e. cooler "streamDigits" method)

This commit is contained in:
2019-12-04 20:15:37 +01:00
parent 1d67f6a52c
commit ab3bf07ec4

View File

@@ -14,7 +14,7 @@ object Day4 {
fun puzzle1() {
val range = line(DAY4_PATH).split('-').map { it.toInt() }
println(IntStream.range(range[0], range[1])
println(IntStream.rangeClosed(range[0], range[1])
.parallel()
.filter(::neverDecrease)
.filter(::repeatingDigits)
@@ -23,17 +23,19 @@ object Day4 {
fun puzzle2() {
val range = line(DAY4_PATH).split('-').map { it.toInt() }
println(IntStream.range(range[0], range[1])
println(IntStream.rangeClosed(range[0], range[1])
.parallel()
.filter(::neverDecrease)
.filter{ n -> IntStream.rangeClosed(1, 9).anyMatch{ repeatsOnlyTwice(n, it)} }
.count())
}
// To explain the magic "reduce" operation below: the "current" value in the reduction will be set to negative as soon as the next value is smaller then it.
// If it is not smaller, the current value will be set to the "next" value, so that it can be evaluated
private fun neverDecrease(n: Int) = streamDigits(n).reduce(0) { a, b -> if (a < 0) a else if (b < a) -1 else b} >= 0
private fun repeatingDigits(n: Int) = streamDigits(n).reduce(-1) { a, b -> if (a == 1000) a else if (a == b) 1000 else b} == 1000
private fun repeatsOnlyTwice(n: Int, needle: Int) = streamDigits(n).filter { it == needle }.count() == 2L
private fun streamDigits(n: Int): IntStream = IntStream.range(0, n.toString().length).map { n.toString()[it].toString().toInt() }
private fun streamDigits(n: Int): IntStream = n.toString().chars().map { it - '0'.toInt() }
}