How to divide a given amount into bills (banknotes) and coins in Ruby

1 Answer

0 votes
#
# Divide a given amount into bills and coins using a greedy algorithm.
# This program is written in idiomatic Ruby, using clear structure,
# functions, built‑in methods, and full explanations.
#

#
# Function: divide_amount
# -----------------------
# Given an amount and a list of bills/coins, prints how many
# of each denomination are needed using a greedy algorithm.
#
# The greedy method is optimal for standard currency systems.
#
def divide_amount(amount, denominations)
  puts "Dividing amount: #{amount}\n\n"

  denominations.each do |d|
    count = amount / d   # integer division
    if count > 0
      puts "#{d}-unit: #{count}"
      amount %= d        # reduce remaining amount
    end
  end

  puts "\nWarning: leftover amount = #{amount}" if amount > 0
end

def main
  bills_coins = [500, 100, 200, 50, 20, 10, 5, 2, 1]

  # Ruby: sort descending using sort.reverse
  denominations = bills_coins.sort.reverse

  amount = 9749

  divide_amount(amount, denominations)
end

main


=begin
run:

Dividing amount: 9749

500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2

=end

 



answered Jul 26 by avibootz
...