added 2024 part 2
This commit is contained in:
64
2024/02/Kotlin/src/main/kotlin/Main.kt
Normal file
64
2024/02/Kotlin/src/main/kotlin/Main.kt
Normal file
@@ -0,0 +1,64 @@
|
||||
package ch.makhankov
|
||||
|
||||
import kotlin.math.absoluteValue
|
||||
import kotlin.math.sign
|
||||
|
||||
fun main() {
|
||||
val filenames = listOf("example.txt", "input.txt")
|
||||
filenames.forEach { filename ->
|
||||
val data = readFile(filename)
|
||||
val dataRows = data?.split("\r\n")
|
||||
val dataEntries = dataRows?.map { it.split(" ") }?.map { it.map { s -> s.toInt() } }
|
||||
val result = dataEntries?.let { calculateSafeRecords(it) }
|
||||
val resultDampened = dataEntries?.let { calculateSafeRecordsWithTolerance(it) }
|
||||
println("Part 1: $result")
|
||||
println("Part 2: $resultDampened")
|
||||
}
|
||||
}
|
||||
|
||||
fun readFile(filename: String): String? {
|
||||
return object {}.javaClass.getResource("/$filename")?.readText()
|
||||
}
|
||||
|
||||
fun diffFromList(list: List<Int>): List<Int> {
|
||||
return list.dropLast(1).mapIndexed { index, i -> i - list[index + 1] }
|
||||
}
|
||||
|
||||
fun sameSign(list: List<Int>): Boolean {
|
||||
val temp = list[0]
|
||||
return list.drop(1).all { it.sign == temp.sign }
|
||||
}
|
||||
|
||||
fun inIncreaseRange(list: List<Int>, range: IntRange): Boolean {
|
||||
return list.all { range.contains(it.absoluteValue) }
|
||||
}
|
||||
|
||||
fun calculateSafeRecords(input: List<List<Int>>): Int {
|
||||
val checkValidity = input.map { transformation(it) }
|
||||
return checkValidity.count { it }
|
||||
}
|
||||
|
||||
fun calculateSafeRecordsWithTolerance(input: List<List<Int>>): Int {
|
||||
val checkValidity = input.map { transformation(it) }
|
||||
var count = checkValidity.count { it }
|
||||
checkValidity.forEachIndexed { index, value ->
|
||||
if (!value) {
|
||||
val record = input[index]
|
||||
for ((rIndex, _) in record.withIndex()) {
|
||||
val subList = record.filterIndexed { i, _ -> i != rIndex }
|
||||
if (transformation(subList)) {
|
||||
count = count.inc()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
fun transformation(input: List<Int>): Boolean{
|
||||
val diffs = diffFromList(input)
|
||||
val sameSign = sameSign(diffs)
|
||||
val inRange = inIncreaseRange(diffs, 1..3)
|
||||
return sameSign && inRange
|
||||
}
|
||||
Reference in New Issue
Block a user