Optimize part1
This commit is contained in:
parent
3399bd8c43
commit
9aa3c1cace
@ -10,23 +10,26 @@ class Day09(@Lines val input: Input<LongArray>) {
|
||||
|
||||
private var part1Result = 0L
|
||||
|
||||
fun part1() = input.value
|
||||
.toList()
|
||||
.asSequence()
|
||||
.windowed(size = 26)
|
||||
.find { !isValid(it) }
|
||||
?.last()
|
||||
?.also { part1Result = it }
|
||||
fun part1(): Long? {
|
||||
val longs = input.value
|
||||
|
||||
private fun isValid(items: List<Long>): Boolean {
|
||||
val preamble = items.take(25)
|
||||
val last = items.last()
|
||||
for (windowStart in 0 until longs.size - 26) {
|
||||
val last = longs[windowStart + 25]
|
||||
if (!isValid(windowStart, last)) {
|
||||
part1Result = last
|
||||
return last
|
||||
}
|
||||
}
|
||||
|
||||
for (e in preamble) {
|
||||
for (f in preamble) {
|
||||
if (e + f == last && e != f) {
|
||||
return true
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun isValid(windowStart: Int, last: Long): Boolean {
|
||||
for (i in windowStart..windowStart + 25) {
|
||||
for (j in windowStart + 1..windowStart + 25) {
|
||||
val f = input.value[i]
|
||||
val s = input.value[j]
|
||||
if (f + s == last && f != s) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user