2024-12-02 13:06:26 +00:00
|
|
|
import java.io.File
|
|
|
|
import java.util.Scanner
|
|
|
|
import kotlin.math.abs
|
|
|
|
|
2024-12-02 13:06:27 +00:00
|
|
|
val scanner = Scanner(File("day02input.txt"))
|
2024-12-02 13:06:26 +00:00
|
|
|
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++
|
|
|
|
}
|
|
|
|
}
|
2024-12-02 13:06:27 +00:00
|
|
|
println("Safe lines: $safelines")
|
|
|
|
println("Safe lines with dampener: ${dampenedsafelines + safelines}")
|
2024-12-02 13:06:26 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|