Created
December 13, 2024 14:46
-
-
Save edreyer/2cc76ba9e0bfff9ad0ddf0739fbf1a51 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getLevels(report: String): List<Int> = report | |
.trim() | |
.split(" ".toRegex()) | |
.filter { it.length > 0 } | |
.map { it.trim().toInt() } | |
fun isSafe(levels: List<Int>): Boolean { | |
// if all diffs are in range, and go all up or all down, it's safe | |
// iterate through and taking once of the numbers out to | |
return (0 until levels.size).any { idx -> | |
val list = levels.toMutableList().apply { this.removeAt(idx) } | |
.zipWithNext() { a, b -> b - a } // convert levels to diffs | |
val allPositive = { list.all { it in (1..3) } } | |
val allNegative = { list.all { it in (-3)..(-1) } } | |
allPositive() || allNegative() | |
} | |
} | |
import java.io.File | |
import java.io.IOException | |
fun readFileContents(filePath: String): String { | |
return try { | |
val file = File(filePath) | |
file.readText() | |
} catch (e: IOException) { | |
"Error reading file: ${e.message}" | |
} | |
} | |
readFileContents("./input.txt") | |
.lines() | |
.filter { isSafe(getLevels(it)) } | |
.size | |
.run { println(this) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment