1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| type Value = Int -- value of a piece
type Reserve = [(Value,Int)] -- couple of (piece value, number of such piece)
type Solution = [(Value,Int)] -- solutions are from the same form
-- the above types can't express an important invariant :
-- the value should be ordered in decreasing order and form a canonic system
-- for the algorithm to deliver correct responses correctly ordered
-- we would need a dependent type system to express those invariants in the types
-- we opted for a function that would use the eager algorithm to
-- deliver all solutions, the optimal first
solve :: Value -> Reserve -> [Solution]
solve 0 [] = [[]]
solve value [] = []
solve value ((pieceValue, amount) : pieces) =
concatMap forAGivenAmount [maxAmount, maxAmount - 1 .. 0]
where maxAmount = min (value `div` pieceValue) amount
forAGivenAmount solAmount =
map ((pieceValue,solAmount) :)
$ solve (value - pieceValue * solAmount) pieces
main = print . head $ solve 80 [(100,0), (50,5), (20,5), (10,0), (5,0), (2,0), (1,0)] |
Partager