burjui

Money exchange solver in Go

Apr 6th, 2012
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.23 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math/big"
  6. )
  7.  
  8. var big_zero = big.NewInt(0)
  9. var big_one = big.NewInt(1)
  10.  
  11. func count_exchanges(sum int, coins []int) *big.Int {
  12.     cache := make([]*big.Int, (sum + 1) * (len(coins) + 1))
  13.    
  14.     var internal_count func (sum int, coin_index int) *big.Int
  15.    
  16.     internal_count = func (sum int, coin_index int) *big.Int {
  17.         switch {
  18.             case sum < 0: return big_zero
  19.             case sum == 0: return big_one
  20.             case coin_index < 0 || coin_index >= len(coins): return big_zero
  21.         }
  22.        
  23.         cached_index := sum + (sum + 1) * coin_index
  24.         cached_value := cache[cached_index]
  25.        
  26.         if cached_value != nil {
  27.             return cached_value
  28.         }
  29.        
  30.         for coin_index < len(coins) && sum < coins[coin_index] {
  31.             coin_index++
  32.         }
  33.        
  34.         result := big.NewInt(0).Add(
  35.             internal_count(sum - coins[coin_index], coin_index),
  36.             internal_count(sum, coin_index + 1))
  37.        
  38.         cache[cached_index] = result
  39.         return result
  40.     }
  41.    
  42.     return internal_count(sum, 0)
  43. }
  44.  
  45. func main() {
  46.     fmt.Printf("%d\n", count_exchanges(1000000, []int { 50, 25, 10, 5, 1 }))
  47. }
Add Comment
Please, Sign In to add comment