Created
January 10, 2021 22:10
-
-
Save thenixan/a7e3efe5d18f9c05bb23055cb7906892 to your computer and use it in GitHub Desktop.
AoC 2020 Day 1
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
import java.io.File | |
fun main(args: Array<String>) { | |
val result = DayOneTask.run() | |
println(result) | |
} | |
object DayOneTask { | |
fun run(): Int { | |
val inputData = File("input") | |
.readLines() | |
.map(String::toInt) | |
return (0 until inputData.size - 2) | |
.mapNotNull { firstPosition -> | |
val first = inputData[firstPosition] | |
val lookup = 2020 - first | |
(firstPosition until inputData.size - 3) | |
.mapNotNull { secondPosition -> | |
inputData | |
.drop(secondPosition) | |
.headWithLeftover(lookup) | |
{ left, right -> | |
left * right | |
} | |
?.let { it * first } | |
}.firstOrNull() | |
} | |
.first() | |
} | |
private fun List<Int>.headWithLeftover( | |
target: Int, | |
f: (Int, Int) -> Int | |
): | |
Int? { | |
if (size < 2) { | |
return null | |
} | |
val head = first() | |
val lookup = target - head | |
return if ( | |
lookup > 0 && | |
drop(1) | |
.contains(lookup) | |
) { | |
f(head, lookup) | |
} else { | |
null | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment