complete day 2
This commit is contained in:
parent
e709c369c5
commit
10e59bd5ba
2 changed files with 82 additions and 0 deletions
33
02-a.kts
Normal file
33
02-a.kts
Normal file
|
@ -0,0 +1,33 @@
|
|||
import java.util.Scanner
|
||||
|
||||
val isSafelyIncreasing = { offset: Int -> offset in 1..3 }
|
||||
|
||||
val isSafelyDecreasing = { offset: Int -> offset in (-3)..(-1) }
|
||||
|
||||
fun isSafeRoute(levels: List<Int>): Boolean {
|
||||
val levelOffsets = levels.foldIndexed(ArrayList<Int>()) { index, acc, i ->
|
||||
if (index > 0) {
|
||||
acc.add(i - levels[index - 1])
|
||||
}
|
||||
acc
|
||||
}
|
||||
|
||||
return levelOffsets.all(isSafelyIncreasing) || levelOffsets.all(isSafelyDecreasing)
|
||||
}
|
||||
|
||||
val scanner = Scanner(System.`in`)
|
||||
|
||||
var safeCount = 0
|
||||
while (scanner.hasNextInt()) {
|
||||
val line = scanner.nextLine()
|
||||
|
||||
val numbers = line.split(" ").map { it.toInt() }
|
||||
|
||||
if (isSafeRoute(numbers)) {
|
||||
safeCount++
|
||||
}
|
||||
}
|
||||
|
||||
println(safeCount)
|
||||
|
||||
|
49
02-b.kts
Normal file
49
02-b.kts
Normal file
|
@ -0,0 +1,49 @@
|
|||
import java.util.Scanner
|
||||
|
||||
val isSafelyIncreasing = { offset: Int -> offset in 1..3 }
|
||||
|
||||
val isSafelyDecreasing = { offset: Int -> offset in (-3)..(-1) }
|
||||
|
||||
fun isSafeRoute(levels: List<Int>): Boolean {
|
||||
val levelOffsets = levels.foldIndexed(ArrayList<Int>()) { index, acc, i ->
|
||||
if (index > 0) {
|
||||
acc.add(i - levels[index - 1])
|
||||
}
|
||||
acc
|
||||
}
|
||||
|
||||
return (levelOffsets.all(isSafelyIncreasing) || levelOffsets.all(isSafelyDecreasing))
|
||||
|
||||
}
|
||||
|
||||
fun isSafeRouteTolerated(levels: List<Int>): Boolean {
|
||||
if (isSafeRoute(levels)) {
|
||||
return true
|
||||
}
|
||||
|
||||
for (skipPos in levels.indices) {
|
||||
val skippedList = levels.slice((0)..<skipPos) + levels.slice((skipPos+1)..levels.lastIndex)
|
||||
if (isSafeRoute(skippedList)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
val scanner = Scanner(System.`in`)
|
||||
|
||||
var safeCount = 0
|
||||
while (scanner.hasNextInt()) {
|
||||
val line = scanner.nextLine()
|
||||
|
||||
val numbers = line.split(" ").map { it.toInt() }
|
||||
|
||||
if (isSafeRouteTolerated(numbers)) {
|
||||
safeCount++
|
||||
}
|
||||
}
|
||||
|
||||
println(safeCount)
|
||||
|
||||
|
Loading…
Add table
Reference in a new issue