Skip to content

Instantly share code, notes, and snippets.

@jvlmdr
Last active August 1, 2023 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvlmdr/e0ddd64beb07f9636875a8619f92505f to your computer and use it in GitHub Desktop.
Save jvlmdr/e0ddd64beb07f9636875a8619f92505f to your computer and use it in GitHub Desktop.
Change in Haskell using an array for memoization
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