Here is a version of the Greedy Coin Changer problem inspired by these Scala and Python solutions.
| Code Block |
|---|
enum UsCoin {
quarter(25), dime(10), nickel(5), penny(1)
UsCoin(v) { value = v }
final value
}
enum OzzieCoin {
fifty(50), twenty(20), ten(10), five(5)
OzzieCoin(v) { value = v }
final value
}
def plural(word, count) {
if (count == 1) return word
word[-1] == 'y' ? word[0..-2] + "ies" : word + "s"
}
def change(currency, amount) {
currency.values().inject([]){ list, coin ->
int count = amount / coin.value
amount = amount % coin.value
list += "$count ${plural(coin.toString(), count)}"
}
}
println change(UsCoin, 71) // => [2 quarters, 2 dimes, 0 nickels, 1 penny]
println change(OzzieCoin, 95) // => [1 fifty, 2 twenties, 0 tens, 1 five]
|
This solution uses Java 5 enums (supported in Groovy 1.5+) but other variations are possible.