Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Functional Programming / Exam1-2021.rkt
blob: e5b96e59bdf6ca1bd46751948c2dad6897523b5c (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#lang racket

;;; Exercise 1

(define (^2 n)
  (* n n))

(define (contains-caar elem lst)
  (define (calc lst ind)
    (cond [(null? lst) #f)]
          [(= (caar lst) elem) ind]
          [else (calc (cdr lst) (add1 ind))])
  (calc lst 0))

(define (digit-occur n)
  (define (calc n ret)
    (cond [(= n 0) ret]
          [()]
      )))

(define (get-distribution n)
  (sort (digit-occur n) (lambda (x y) (< (car x) (car y)))))

;;; Exercise 2

(define (find-missing lst)
  (cond [(null? lst) #f]
        [(> (- (cadr lst) (car lst)) 1) (add1 (car lst))]
        [else (find-missing (cdr lst))]))

(define (get-missing-length xss)
  (define lenlis (map (lambda (lst) (length lst)) xss))
  (find-missing (sort lenlis <)))

(get-missing-length '((1 2) (4 5 1 1) (1) (5 6 7 8 9))) ; → 3
(get-missing-length '(("a", "a", "a") ("a", "a") ("a", "a", "a","a") ("a") ("a", "a", "a", "a", "a", "a"))) ; → 5

;;; Exercise 3

(define (biggest-5^k-lt n)
  (define (calc current)
    (if (> current n)
      (quotient current 5)
      (calc (* current 5))))
  (calc 5))

(define (trailing-of-n n)
  (define (calc 5^k sum)
    (if (= 5^k 1)
      sum
      (calc (quotient 5^k 5) (+ sum (floor (/ n 5^k))))))
  (calc (biggest-5^k-lt n) 0))

(define (trailing-zeros n)
  (lambda (p)
    (p (trailing-of-n n))))

((trailing-zeros 6) even?) ; → #f (броят на влачещите нули е 1. 1 не е четно)
((trailing-zeros 1000) even?) ; → #f (броят на влачещите нули е 249. 249 не е четно)
((trailing-zeros 100000) even?) ; → #f (броят на влачещите нули е 24999. 24999 не е четно)
((trailing-zeros 1000000000) even?) ; → #t (броят на влачещите нули е 249999998. 249999998 е четно)

;;; Exercise 4

(define (mult-digits n)
  (define (calc n current)
    (if (= n 0)
      current
      (calc (quotient n 10) (* current (remainder n 10)))))
  (calc n 1))

(define (list-md n)
  (define (calc n res)
    (if (< n 10)
      res
      (calc (mult-digits n) (append res (list (mult-digits n))))))
  (calc n '()))

(define (persistence n)
  (define ys (if (< n 10) (list n) (list-md n)))
  (cons ys (length ys)))

(persistence 39) ; → '((27 14 4) . 3) ; 3*9=27, 2*7=14, 1*4=4
(persistence 126) ; → '((12 2) . 2) ; 1*2*6=12, 1*2=2
(persistence 4) ; → '((4) . 1)
(persistence 999) ; → '((729 126 12 2) . 4)