Skip to content

Instantly share code, notes, and snippets.

@sharkdp
Created June 4, 2015 12:49
Show Gist options
  • Save sharkdp/37b29826f9e071765f4a to your computer and use it in GitHub Desktop.
Save sharkdp/37b29826f9e071765f4a to your computer and use it in GitHub Desktop.
Find the smallest number of coins to represent all numbers between 1 and 99
import Data.List
coins :: [Int]
coins = [1, 2, 5, 10, 20, 50]
type CoinSet = [Int]
-- | All coinsets of a given length
draw :: Int -> [CoinSet]
draw 0 = [[]]
draw n = [ c:cs | c <- coins, cs <- draw (n-1) ]
-- | Can a given coinset represent the number s?
represent :: CoinSet -> Int -> Bool
represent cs s = any (\css -> sum css == s) (subsequences cs)
-- | Can it represent all numbers from 1..99?
representAll :: CoinSet -> Bool
representAll cs = all (represent cs) [1..99]
-- | Find shortest coinset
shortest :: Maybe CoinSet
shortest = find representAll allCS
where allCS = concatMap draw [1..]
main = print shortest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment