burjui

Money exchange solver in Haskell - cached version

Oct 10th, 2012
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.Maybe
  2. import Data.List
  3. import qualified Data.Map as Map
  4.  
  5. countExchanges :: (Integral a) => a -> [a] -> a
  6. countExchanges sum coins = fst $ count sum sorted_coins Map.empty
  7.     where count _ [] cache = (0, cache)
  8.           count sum coins cache
  9.               | isJust cached = (fromJust cached, cache)
  10.               | sum == 0      = memorize 1 cache
  11.               | sum < 0       = memorize 0 cache
  12.               | otherwise     = let (left, updated_cache) = count (sum - head coins) coins cache
  13.                                     (right, final_cache)  = count sum (tail coins) updated_cache
  14.                                 in
  15.                                     memorize (left + right) final_cache
  16.               where cached = Map.lookup key cache
  17.                     key = (sum, head coins)
  18.                     memorize result target_cache = (result, Map.insert key result target_cache)
  19.           sorted_coins = reverse $ sort coins
  20.  
  21. main = print (countExchanges 100000 [50, 25, 10, 5, 1])
Add Comment
Please, Sign In to add comment