Change machine

Start of the year, some fun stuff.

I recently had some spare time and re-visited my first ever uni assignment. The problem it’s trying to solve is easy, given any amount of money in cents, figure out the minimium number of coins required. No need to say, the little Java program I wrote was crazily bad. So I rewrote it again in Ruby.

And here’s my solution after over 10 years of programming practice :)

module ChangeMachine

  class IdiotEncountered < StandardError; end

  AVAILABLE_UNITS = [10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5]

  def self.show_me_the_money(dollar_in_cents)
    raise IdiotEncountered, "You are an idiot, no such amount in AUS..." unless dollar_in_cents % 5 == 0

  def self.dispense(dollar_in_cents)
    return {} if dollar_in_cents == 0

    unit ={|u| u <= dollar_in_cents}.max
    {unit => (dollar_in_cents / unit)}.merge(dispense(dollar_in_cents % unit))

puts ChangeMachine.show_me_the_money(37500).inspect
# => {10000=>3, 5000=>1, 2000=>1, 500=>1}

My Java version can be found here under the comments section.

Published: 2013-01-04
blog comments powered by Disqus