Last active
October 19, 2019 11:21
-
-
Save jacoelho/f4ec9923f75af440eb30ed6580b72549 to your computer and use it in GitHub Desktop.
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
// coin change kata | |
fun largestCoin(coins: IntArray, amount: Int): Int? = | |
try { | |
coins.first { coin -> coin <= amount } | |
} catch (_: NoSuchElementException) { | |
null | |
} | |
fun coinChange(coins: IntArray, amount: Int): Int { | |
val coinsSorted = coins.sortedArrayDescending() | |
tailrec fun recur(count: Int = 0, amount: Int): Int { | |
return if (amount == 0) { | |
count | |
} else { | |
val coin = largestCoin(coinsSorted, amount) ?: return -1 | |
recur(count + 1, amount - coin) | |
} | |
} | |
return recur(amount = amount) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment