Last active
November 25, 2019 09:11
-
-
Save LukasForst/70cb04cf2939db243762944e5ac1344a to your computer and use it in GitHub Desktop.
One-Liner for coin change
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
fun main() { | |
val toChange = 132 | |
val coins = listOf(50, 20, 10, 5, 2, 1).sortedDescending() | |
coins.fold(Pair(toChange, emptyList<Int>())) { (remaining, change), coin -> (remaining % coin) to (change + (remaining / coin)) } | |
.also { (remaining, change) -> | |
assert(0 == remaining) | |
print(change.zip(coins).joinToString(", ") { (change, coin) -> "$coin: ${change}x" }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment