Skip to content

Instantly share code, notes, and snippets.

@jaksonmoura
Created October 3, 2011 15:38
Show Gist options
  • Select an option

  • Save jaksonmoura/1259391 to your computer and use it in GitHub Desktop.

Select an option

Save jaksonmoura/1259391 to your computer and use it in GitHub Desktop.
Troco
require 'test/unit'
require "./Troco.rb"
class TestTroco < Test::Unit::TestCase
def setup
@t = Troco.new
end
def teardown
@t = nil
end
def test_troco_cedulas
assert_equal(nil, @t.trocar(150, 144))
assert_equal([2, 0], @t.trocar(10, 16))
assert_equal([0, 0], @t.trocar(10, 10))
end
def test_troco_moedas
assert_equal([0,1], @t.trocar(0.50, 1.00))
assert_equal([0,5], @t.trocar(0.55, 1.00))
assert_equal([0,5], @t.trocar(0.24, 1.00))
end
def test_troco_cedulas_moedas
assert_equal([2,2], @t.trocar(10.00, 12.20))
end
end
# http://dojopuzzles.com/problemas/exibe/troco/
class Troco
def trocar(total, pago)
return [0, 0] if total == pago
return nil if pago < total
pago, total = pago.to_f, total.to_f
troco = 0.00
troco = pago - total if pago > total
cedulas = [100.00, 50.00, 10.00, 5.00, 1.00]
moedas = [0.50, 0.10, 0.05, 0.01]
t_cedulas, t_moedas = 0, 0
cedulas.each do |c|
if troco >= c
t_cedulas += (troco % c)
troco -= (c*(troco % c))
if troco % c == 0
t_cedulas += troco/c
troco -= 1.0
end
end
end
moedas.each do |m|
if troco >= m
aux = 0
aux = (troco/m).to_i
troco = (troco - (aux * m)).round(2)
t_moedas += aux
end
end
return [t_cedulas.to_i, t_moedas.to_i]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment