From 6f2b0cf726a93149615b22bf6f615c496b885176 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 14 Aug 2017 15:00:28 -0400 Subject: [PATCH] Kotlin - Change Complete --- kotlin/change/src/main/kotlin/Change.kt | 38 +++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/kotlin/change/src/main/kotlin/Change.kt b/kotlin/change/src/main/kotlin/Change.kt index 98577d0..67b456d 100644 --- a/kotlin/change/src/main/kotlin/Change.kt +++ b/kotlin/change/src/main/kotlin/Change.kt @@ -1,10 +1,11 @@ class Change(val setOfCoins: Set) { - fun issue(x: Int): List{ + // This is a good greedy implementation of the algorithm + fun issue_greedy(x: Int): List { require((x > setOfCoins.min()!!) or (x == 0)) var y = x val returnList = mutableListOf() - - while (y != 0){ + + while (y != 0) { val maxChange = setOfCoins.filter { y >= it }.max() returnList.add(maxChange ?: 0) y -= maxChange ?: 0 @@ -12,4 +13,35 @@ class Change(val setOfCoins: Set) { return returnList.reversed() } + + val resultMap: MutableMap> = mutableMapOf>() + + fun issue(x: Int): List { + require((x >= setOfCoins.min()!!) or (x == 0)) + if (x == 0) { + return emptyList() + } else if (x in setOfCoins) { + return listOf(x) + } else if (x in resultMap){ + return resultMap[x]!! + } else { + for (i in setOfCoins.filter { it <= x }) { + val firstCandidate = issue(x - i) + i + if (resultMap[x]?.isEmpty() ?: true){ + resultMap[x] = firstCandidate + } + if (firstCandidate.size < resultMap[x]?.size ?: 1000){ + resultMap[x] = firstCandidate + } + } + } + + return resultMap[x]!!.sorted() + } +} + + +fun main(args: Array) { + print(Change(setOf(1, 5, 10, 21, 25)).issue(63)) + print(Change(setOf(1, 4, 15, 20, 50)).issue(23)) } \ No newline at end of file