Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Functional Programming / hw2.rkt
blob: c0f4223642543f7e07672a7a8be2342309bfad21 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#lang racket

;;; Задача 1

(define (pair-compose fs xs)
  (cond [(= (length fs) 0) 0]
        [(= (length fs) 1) (lambda (y) ((car fs) (car xs) y))]
        [else (lambda (y) (+ ((first fs) (first xs) ((second fs) (second xs) y))
                             ((pair-compose (cdr (cdr fs)) (cdr (cdr xs))) y) ))]))

;; Примери
(define fs (list *
                 (lambda (x y) (* x x x y))
                 (lambda (x y) (+ x 1 y))
                 (lambda (x y) (- x (+ 1 y)))
                 (lambda (x y) (* x y 2))))
(define xs '(1 2 3 4 5))
((pair-compose fs xs) 5) ; → 92

;;; Задача 2

(define (inside-range? point range)
  (and (<= (car range) point) (>= (cdr range) point)))

(define (range-covers? range ranges)
  (cond [(null? ranges) #f]
        [(or (inside-range? (car range) (car ranges)) (inside-range? (cdr range) (car ranges))) #t]
        [else (range-covers? range (cdr ranges))]))

(define (woodcutters xs)
  (define (calc-check xs fallen count)
    (if (null? xs)
      count
      (calc xs fallen count)))
  (define (calc xs fallen count)
    
    (define leftRange (cons (- (car (car xs)) (cdr (car xs))) (car (car xs))))
    (define rightRange (cons (cdr (car xs)) (+ (car (car xs)) (cdr (car xs)))))

    (define withLeft (if (range-covers? leftRange fallen)
                         0
                         (calc-check (cdr xs) (list* leftRange fallen) (add1 count))))
    (define withRight (if (range-covers? rightRange fallen)
                          0
                          (calc-check (cdr xs) (list* rightRange fallen) (add1 count))))
    (define noRange (calc-check (cdr xs) fallen count))

    (max withLeft withRight noRange))
  (calc-check xs '() 0))

(woodcutters '((1 . 2) (2 . 1) (5 . 10) (10 . 9) (19 . 1))) ; → 3
(woodcutters '((1 . 2) (2 . 1) (5 . 10) (10 . 9) (20 . 1))) ; → 4
(woodcutters '((10 . 4) (15 . 1) (19 . 3) (20 . 1))) ; → 4
; (woodcutters '((1 . 7) (3 . 11) (6 . 12) (7 . 6) (8 . 5) (9 . 11)
; (15 . 3) (16 . 10) (22 . 2) (23 . 3) (25 . 7) (27 . 3) (34 . 5)
; (35 . 10) (37 . 3) (39 . 4) (40 . 5) (41 . 1) (44 . 1) (47 . 7)
; (48 . 11) (50 . 6) (52 . 5) (57 . 2) (58 . 7) (60 . 4) (62 . 1)
; (67 . 3) (68 . 12) (69 . 8) (70 . 1) (71 . 5) (72 . 5)
; (73 . 6) (74 . 4) ) ) ; → 10