Permalink
Browse files

Add 2_40 and 2_41

  • Loading branch information...
fastred committed Dec 29, 2012
1 parent 3dbd69a commit 1391201fe190f54781487ef79fc7e18e5f42b050
Showing with 71 additions and 0 deletions.
  1. +41 −0 2_40.scm
  2. +30 −0 2_41.scm
View
@@ -0,0 +1,41 @@
+(define (enumerate-interval low high)
+ (if (> low high)
+ '()
+ (cons low (enumerate-interval (+ low 1) high))))
+(define (accumulate op initial sequence)
+ (if (null? sequence)
+ initial
+ (op (car sequence)
+ (accumulate op initial (cdr sequence)))))
+(define (flatmap proc seq)
+ (accumulate append '() (map proc seq)))
+(define (prime-sum? pair)
+ (prime? (+ (car pair) (cadr pair))))
+(define (square n)
+ (* n n))
+(define (divides? a b)
+ (= (remainder b a) 0))
+(define (find-divisor n test-divisor)
+ (cond ((> (square test-divisor) n) n)
+ ((divides? test-divisor n) test-divisor)
+ (else (find-divisor n (+ test-divisor 1)))))
+(define (smallest-divisor n)
+ (find-divisor n 2))
+(define (prime? n)
+ (= n (smallest-divisor n)))
+(define (make-pair-sum pair)
+ (list (car pair) (cadr pair) (+ (car pair) (cadr pair))))
+
+(define (unique-pairs n)
+ (flatmap (lambda (i)
+ (map (lambda (j) (list i j))
+ (enumerate-interval 1 (- i 1))))
+ (enumerate-interval 1 n)))
+(define (prime-sum-pairs n)
+ (map make-pair-sum
+ (filter prime-sum?
+ (unique-pairs n))))
+
+
+
+
View
@@ -0,0 +1,30 @@
+(define (enumerate-interval low high)
+ (if (> low high)
+ '()
+ (cons low (enumerate-interval (+ low 1) high))))
+(define (accumulate op initial sequence)
+ (if (null? sequence)
+ initial
+ (op (car sequence)
+ (accumulate op initial (cdr sequence)))))
+(define (flatmap proc seq)
+ (accumulate append '() (map proc seq)))
+(define (make-pair-sum pair)
+ (list (car pair) (cadr pair) (+ (car pair) (cadr pair))))
+(define (unique-pairs n)
+ (flatmap (lambda (i)
+ (map (lambda (j) (list i j))
+ (enumerate-interval 1 (- i 1))))
+ (enumerate-interval 1 n)))
+
+(define (sum-of-triple a)
+ (+ (car a) (cadr a) (caddr a)))
+(define (triples-that-sum n k)
+ (filter (lambda (a) (= (sum-of-triple a) k))
+ (flatmap (lambda (i)
+ (flatmap (lambda (j)
+ (map (lambda (k) (list i j k))
+ (enumerate-interval 1 (- j 1))))
+ (enumerate-interval 1 (- i 1))))
+ (enumerate-interval 1 n))))
+

0 comments on commit 1391201

Please sign in to comment.