Skip to content

Instantly share code, notes, and snippets.

@thenixan
Created January 10, 2021 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thenixan/a7e3efe5d18f9c05bb23055cb7906892 to your computer and use it in GitHub Desktop.
Save thenixan/a7e3efe5d18f9c05bb23055cb7906892 to your computer and use it in GitHub Desktop.
AoC 2020 Day 1
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