Question
In England the currency is made up of pounds, £, and pence, p, and there are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p)
It is possible to make £2 in the following way:
1 × £1 + 1 × 50p + 2 × 20p + 1 × 5p + 1 × 2p + 3 × 1p
How many different ways can £2 be made using any number of coins?
Haskell
= print $ length [1 | a <- [200,0],
main <- [a,a-100..0],
b <- [b,b-50..0],
c <- [c,c-20..0],
d <- [d,d-10..0],
e <- [e,e-5..0],
f <- [f,f-2..0]] g
$ ghc -O2 -o currency currency.hs
$ time ./currency
real 0m0.004s
user 0m0.000s
sys 0m0.004s
Python
#!/usr/bin/env python
def ways_to_change(target, coins):
if target == 0 or len(coins) == 1:
return 1
else:
= sorted(coins)
coins = coins[-1]
largest = target // largest
uses = 0
total for i in range(uses + 1):
+= ways_to_change(target - largest * i, coins[:-1])
total return total
def main():
print(ways_to_change(200, [1, 2, 5, 10, 20, 50, 100, 200]))
if __name__ == "__main__":
main()
$ time python3 currency.py
real 0m0.049s
user 0m0.049s
sys 0m0.000s
Ruby
#!/usr/bin/env ruby
= 0
count 200.step(0, -200) do |a|
.step(0, -100) do |b|
a.step(0, -50) do |c|
b.step(0, -20) do |d|
c.step(0, -10) do |e|
d.step(0, -5) do |f|
e.step(0, -2) do
f+= 1
count end
end
end
end
end
end
end
puts count
$ time ruby currency.rb
real 0m0.043s
user 0m0.043s
sys 0m0.000s