aoc_2024/puzzle2.kts
2024-12-02 14:06:26 +01:00

49 lines
1.3 KiB
Kotlin

import java.io.File
import java.util.Scanner
import javax.print.attribute.standard.NumberUpSupported
import kotlin.math.abs
val scanner = Scanner(File("puzzle2input.txt"))
var safelines = 0
var dampenedsafelines = 0
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
val numbers = line.split(" ").map { it.toInt() }
if (isSafe(numbers)) {
safelines++
} else if (dampenedSafe(numbers)) {
dampenedsafelines++
}
}
println(safelines)
println(dampenedsafelines + safelines)
fun isSafe(numbers: List<Int> ): Boolean {
var directionality = 0
for (i in 1 until numbers.size) {
val direction = if (numbers[i] > numbers[i - 1]) 1 else -1
if (directionality == 0) {
directionality = direction
} else if (directionality != direction) {
return false
}
val difference = abs(numbers[i] - numbers[i - 1])
if (difference < 1 || difference > 3) {
return false
}
}
return true
}
fun dampenedSafe(numbers: List<Int>): Boolean {
// Brute force approach
for (i in numbers.indices) {
val copy = numbers.toMutableList()
copy.removeAt(i)
if (isSafe(copy)) {
return true
}
}
return false
}