Guest User

Untitled

a guest
Jan 20th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. (define ht (make-hashtable equal-hash equal?))
  2.  
  3. (define (count-change-crappy sum . coins)
  4. (cond
  5. ((= sum 0) 1)
  6. ((or (null? coins) (< sum 0)) 0)
  7. (else
  8. (+ (apply count-change-crappy (cons sum (cdr coins)))
  9. (apply count-change-crappy (cons (- sum (car coins)) coins)))
  10. )
  11. )
  12. )
  13.  
  14. (define (count-change-memoized sum . coins)
  15. (cond
  16. ((= sum 0) 1)
  17. ((or (null? coins) (< sum 0)) 0)
  18. (else
  19. (let ((key1 (cons sum (cdr coins)))
  20. (key2 (cons (- sum (car coins)) coins)))
  21. (if (not (hashtable-contains? ht key1))
  22. (hashtable-set! ht key1 (apply count-change-memoized key1))
  23. )
  24. (if (not (hashtable-contains? ht key2))
  25. (hashtable-set! ht key2 (apply count-change-memoized key2))
  26. )
  27. (+ (hashtable-ref ht key1 0)
  28. (hashtable-ref ht key2 0))
  29. )
  30. )
  31. )
  32. )
  33.  
  34. (define (time f . args)
  35. (define before (js-invoke (js-new "Date") "getTime"))
  36. (define result (apply f args))
  37. (define after (js-invoke (js-new "Date") "getTime"))
  38. (print "Ran for " (- after before) " ms, Number of combinations: " result)
  39. )
  40.  
  41. (time count-change-memoized 100 1 2 3 6 9)
  42. (time count-change-crappy 100 1 2 3 6 9)
Add Comment
Please, Sign In to add comment