Skip to content

Commit e71bf7a

Browse files
committed
Add implementation of exercise 3-71
1 parent de352ec commit e71bf7a

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

README.org

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
习题完成情况:
2626
- 章节一: 43/46
2727
- 章节二: 88/97
28-
- 章节三: 64/82
28+
- 章节三: 65/82
2929
- 章节四: TODO
3030
- 章节五: TODO
3131
* 运行

chapter3/exercise3-70.rkt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
(stream-cdr t))
2727
(pairs-weighted (stream-cdr s) (stream-cdr t) weight)
2828
weight))))
29+
(provide pairs-weighted merge-weighted)
2930

3031
(module+ test
3132
(require rackunit)

chapter3/exercise3-71.rkt

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#lang racket
2+
(require "stream.rkt")
3+
(require "infinite-stream.rkt")
4+
(require "exercise3-70.rkt")
5+
6+
(define cube-weight (lambda (pair) (let ((i (car pair))
7+
(j (cadr pair)))
8+
(+ (* i i i)
9+
(* j j j)))))
10+
(define cube-sum-stream (pairs-weighted integers integers cube-weight))
11+
12+
(define (find-ramanujan-numbers s)
13+
(if (or (stream-null? s)
14+
(stream-null? (stream-cdr s)))
15+
(error "The given stream is empty")
16+
(let* ((first (stream-car s))
17+
(second (stream-car (stream-cdr s)))
18+
(first-w (cube-weight first))
19+
(second-w (cube-weight second)))
20+
(if (= first-w second-w)
21+
;; 找到权重相同的前后相邻两个序对
22+
(cons-stream
23+
(list first-w first second)
24+
;; 将有后面有相同权重的序对排除
25+
(find-ramanujan-numbers (stream-filter (lambda (x) (not (= (cube-weight x) first-w)))
26+
(stream-cdr s)))
27+
)
28+
;; 没找到,递归寻找
29+
(find-ramanujan-numbers (stream-cdr s) )))))
30+
31+
(define ramanujan-stream (find-ramanujan-numbers cube-sum-stream))
32+
33+
(module+ test
34+
(require rackunit)
35+
36+
(test-case "Test for ramanujan-numbers"
37+
(check-equal? (stream-take-n ramanujan-stream 5) '((1729 (1 12) (9 10))
38+
(4104 (2 16) (9 15))
39+
(13832 (2 24) (18 20))
40+
(20683 (10 27) (19 24))
41+
(32832 (4 32) (18 30)))))
42+
)

0 commit comments

Comments
 (0)