timothy235

sicp-4-3-1-amb-and-search

Mar 20th, 2017 (edited)
797
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.44 KB | None | 0 0
  1. #lang racket
  2.  
  3. ;;;;;;;;;;
  4. ;; 4.35 ;;
  5. ;;;;;;;;;;
  6.  
  7. (define (an-integer-between low high)
  8.   (my-require (<= low high))
  9.   (amb low (an-integer-between (add1 low) high)))
  10.  
  11. ;; or equivalently:
  12.  
  13. (define (an-integer-between2 low high)
  14.   (an-element-of (range low (add1 high))))
  15.  
  16. ;;;;;;;;;;
  17. ;; 4.36 ;;
  18. ;;;;;;;;;;
  19.  
  20. ;; Depth-first search would search all k values before incrementing i or j.  So we
  21. ;; would never see a triple like (1, 2, 2).  We would only see (1, 1, 1), (1, 1, 2),
  22. ;; (1, 1, 3), etc.
  23.  
  24. ;; Define the weight of a triple to be the sum of its indices.  Then search through
  25. ;; triples by weight:
  26.  
  27. (define (a-triple-of-weight n)
  28.   (let* ([i (an-integer-between 1 n)]
  29.          [j (an-integer-between i n)]
  30.          [k (an-integer-between j n)])
  31.     (my-require (= (+ i j k) n))
  32.     (list i j k)))
  33.  
  34. ;; Combine this with an-integer-starting-from to eventually get all triples:
  35.  
  36. (define (an-integer-starting-from n)
  37.   (amb n (an-integer-starting-from (add1 n))))
  38.  
  39. (define (a-triple)
  40.   (let ([n (an-integer-starting-from 3)])
  41.     (a-triple-of-weight n)))
  42.  
  43. ;;;;;;;;;;
  44. ;; 4.37 ;;
  45. ;;;;;;;;;;
  46.  
  47. ;; Ben's solution will be much faster for large values of high.  He searches for i
  48. ;; through the same range.  He searches for j through a smaller range, because of the
  49. ;; hsq >= ksq requirement.  And he doesn't search for k at all.  He determines k from
  50. ;; i and j.
  51.  
  52. ;; I think the first approach will be O(n^3) and Ben's will be O(n^2).
Advertisement