Created
December 1, 2020 18:49
-
-
Save chutchinson/11522227c05dbb77a5c74a827616e811 to your computer and use it in GitHub Desktop.
Advent of Code 2020 Kotlin
This file contains 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 | |
import java.util.* | |
// https://rosettacode.org/wiki/Combinations#Kotlin | |
inline fun <reified T> combinations(arr: List<T>, m: Int) = sequence { | |
val n = arr.size | |
val result = Array(m) { arr[0] } | |
val stack = LinkedList<Int>() | |
stack.push(0) | |
while (stack.isNotEmpty()) { | |
var resIndex = stack.size - 1; | |
var arrIndex = stack.pop() | |
while (arrIndex < n) { | |
result[resIndex++] = arr[arrIndex++] | |
stack.push(arrIndex) | |
if (resIndex == m) { | |
yield(result.toList()) | |
break | |
} | |
} | |
} | |
} | |
fun findExpense(expenses: List<Int>, n: Int): Int { | |
val combinations = combinations(expenses, n); | |
val tuple = combinations.find() { it.fold(0) { acc, e -> acc + e } == 2020 }!! | |
tuple.fold(1) { fac, e -> fac * e } | |
} | |
fun main(args: Array<String>) { | |
val expenses = File("1.txt") | |
.useLines { it.toList() } | |
.map { Integer.parseInt(it) } | |
var expense1 = findExpense(expenses, 2) | |
println(expense1) | |
var expense2 = findExpense(expenses, 3) | |
println(expense2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment