Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 divMod(dividend, divisor) {
  [dividend.intdiv(divisor), dividend % divisor]
}

def plural(word, count) {
  if (count == 1) return word
  word[-1] == 'y' ? word[0..-2] + "ies" : word + "s"
}

def change(currency, amount) {
  def count
  currency.values().inject([]){ list, coin ->
     [int count, = amount]  / coin.value
     amount = divMod(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+) and Groovy 1.6 multi-assignment, but other variations are possible.