|
| 1 | +#lang racket |
| 2 | +(require "stream.rkt") |
| 3 | +(require "infinite-stream.rkt") |
| 4 | + |
| 5 | +(define (merge-weighted s1 s2 weight) |
| 6 | + (cond ((stream-null? s1) s2) |
| 7 | + ((stream-null? s2) s1) |
| 8 | + (else |
| 9 | + (let* ((s1-head (stream-car s1)) |
| 10 | + (s2-head (stream-car s2)) |
| 11 | + (w1 (weight s1-head)) |
| 12 | + (w2 (weight s2-head))) |
| 13 | + (cond ((<= w1 w2) |
| 14 | + (cons-stream s1-head (merge-weighted (stream-cdr s1) s2 weight))) |
| 15 | + (else |
| 16 | + (cons-stream s2-head (merge-weighted s1 (stream-cdr s2) weight)))))))) |
| 17 | + |
| 18 | +(define (pairs-weighted s t weight) |
| 19 | + (if (or (stream-null? s) |
| 20 | + (stream-null? t)) |
| 21 | + the-empty-stream |
| 22 | + (cons-stream |
| 23 | + (list (stream-car s) (stream-car t)) |
| 24 | + (merge-weighted |
| 25 | + (stream-map (lambda (x) (list (stream-car s) x)) |
| 26 | + (stream-cdr t)) |
| 27 | + (pairs-weighted (stream-cdr s) (stream-cdr t) weight) |
| 28 | + weight)))) |
| 29 | + |
| 30 | +(module+ test |
| 31 | + (require rackunit) |
| 32 | + |
| 33 | + (define not-div-by-2-3-5 |
| 34 | + (stream-filter |
| 35 | + (lambda (x) |
| 36 | + (not (or (= (remainder x 2) 0) |
| 37 | + (= (remainder x 3) 0) |
| 38 | + (= (remainder x 5) 0)))) |
| 39 | + integers)) |
| 40 | + |
| 41 | + (test-case "Test for merge-weighted" |
| 42 | + (define s1 (list-to-stream '(1 2 3 5 7))) |
| 43 | + (define s2 (list-to-stream '(2 -4 5 8 9))) |
| 44 | + (define weight (lambda (x) (abs x))) |
| 45 | + (define s3 (merge-weighted s1 s2 weight)) |
| 46 | + (check-equal? (stream-to-list s3 10) '(1 2 2 3 -4 5 5 7 8 9)) |
| 47 | + ) |
| 48 | + |
| 49 | + (test-case "Test for pairs-weighted with weight = i+j" |
| 50 | + (define s1 (list-to-stream '(1 2 3))) |
| 51 | + (define s2 (list-to-stream '(1 2 3))) |
| 52 | + (define weight (lambda (pair) (+ (car pair) (cadr pair)))) |
| 53 | + (define s3 (pairs-weighted s1 s2 weight)) |
| 54 | + (check-equal? (stream-to-list s3 10) '((1 1) (1 2) (1 3) (2 2) (2 3) (3 3))) |
| 55 | + ) |
| 56 | + |
| 57 | + (test-case "Test for pairs-weighted with weight = 2j + 3j + 5ij" |
| 58 | + (define weight (lambda (pair) (let ((i (car pair)) |
| 59 | + (j (cadr pair))) |
| 60 | + (+ (* 2 i) |
| 61 | + (* 3 j) |
| 62 | + (* 5 i j))))) |
| 63 | + (define result (pairs-weighted not-div-by-2-3-5 not-div-by-2-3-5 weight)) |
| 64 | + (check-equal? (stream-to-list result 5) '((1 1) (1 7) (1 11) (1 13) (1 17)))) |
| 65 | + ) |
0 commit comments