Skip to content

Instantly share code, notes, and snippets.

@devth
Last active December 18, 2015 19:29
Show Gist options
  • Select an option

  • Save devth/5833398 to your computer and use it in GitHub Desktop.

Select an option

Save devth/5833398 to your computer and use it in GitHub Desktop.
Given an amount of money (in cents), determine all the ways to make change given a list of denominations.
change :: Int -> [Int] -> [[Int]]
change amt [] = [[]]
change amt [d] = [replicate (quot amt d) d]
change amt (d:denoms) =
if d <= amt then
reverse [0..(quot amt d)] >>= \x ->
[(replicate x d) ++ c | c <- (change (amt - (x*d)) denoms)]
else
change amt denoms
changeUS amt = change amt [25, 10, 5, 1]
-- *Main> changeUS 29
-- [[25,1,1,1,1],[10,10,5,1,1,1,1],[10,10,1,1,1,1,1,1,1,1,1],[10,5,5,5,1,1,1,1],[10,5,5,1,1,1,1,1,1,1,1,1],[10,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[10,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[5,5,5,5,5,1,1,1,1],[5,5,5,5,1,1,1,1,1,1,1,1,1],[5,5,5,1,1,1,1,1,1,1,1,1,11,1,1,1],[5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment