Created
June 4, 2015 12:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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