Last active
August 1, 2023 00:41
-
-
Save jvlmdr/e0ddd64beb07f9636875a8619f92505f to your computer and use it in GitHub Desktop.
Change in Haskell using an array for memoization
This file contains hidden or 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
module Change (findFewestCoins) where | |
import Data.Array (listArray, (!)) | |
import Data.Function (on) | |
import Safe.Foldable (minimumByMay) | |
findFewestCoins :: Integer -> [Integer] -> Maybe [Integer] | |
findFewestCoins target coins = | |
let solutions = listArray (0, target) $ map formSolution [0 .. target] | |
lookupSolution x = case compare x 0 of | |
LT -> Nothing | |
EQ -> Just [] | |
GT -> solutions ! fromInteger x | |
formSolution x = | |
let solns = map (lookupSolution . (x -)) coins | |
candidates = [coin : soln | (coin, Just soln) <- zip coins solns] in | |
minimumByMay (compare `on` length) candidates in | |
lookupSolution target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment