I decided to make a program that calculates change, based on an input. My code is extremely long, and I would like to know how I can fix this.
def make_change(amount)
values = []
coins = []
hash = {}
if amount >= 50
coins.push(:H)
values.push(amount / 50)
amount = amount % 50
if amount % 50 >= 25
coins.push(:Q)
values.push(amount / 25)
amount = amount % 25
if amount % 25 >= 10
coins.push(:D)
values.push(amount / 10)
amount = amount % 10
if amount % 10 >= 5
coins.push(:N)
values.push(amount / 5)
amount = amount % 5
if amount % 5 >= 1
coins.push(:P)
values.push(amount / 1)
end
end
end
end
elsif amount >= 25
coins.push(:Q)
values.push(amount / 25)
amount = amount % 25
if amount % 25 >= 10
coins.push(:D)
values.push(amount/10)
amount = amount % 10
if amount % 10 >= 5
coins.push(:N)
values.push(amount/5)
amount = amount % 5
if amount % 5 >= 1
coins.push(:P)
values.push(amount/1)
end
end
end
elsif amount >= 10
coins.push(:D)
values.push(amount / 10)
amount = amount % 10
if amount % 10 >= 5
coins.push(:N)
values.push(amount / 5)
amount = amount % 5
if amount % 5 >= 1
coins.push(:P)
values.push(amount / 1)
end
end
elsif amount >= 5
coins.push(:N)
values.push(amount / 5)
amount = amount % 5
if amount % 5 >= 1
coins.push(:P)
values.push(amount / 1)
end
elsif amount >= 1
coins.push(:P)
values.push(amount / 1)
else
coins = []
values = []
end
Hash[coins.zip(values)]
end
Examples
make_change(42) should result in
=> {:Q => 1, :D => 1, :N => 1, :P => 2
make_change(91) should result in
=> {:H => 1, :Q => 1, :D => 1, :N => 1, :P => 1
amountis the amount of change to provide. \$\endgroup\$make_change(23)and get{:D=>2}. Is it an error and the:P=>3is missing? \$\endgroup\$