-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday4.rkt
77 lines (59 loc) · 2.59 KB
/
day4.rkt
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
#lang racket
(require point-free rackunit)
(provide part1 part2 tests)
(define input (file->string "input/d4"))
(define (part1) (count valid1? (make-passports input)))
(define (part2) (count valid2? (make-passports input)))
(define/compose make-passports
(curry map (curryr string-replace " " "\n"))
(curryr string-split "\n\n"))
(define (valid1? passport)
(andmap (curry string-contains? passport)
'("byr:" "iyr:" "eyr:" "hgt:" "hcl:" "ecl:" "pid:")))
(define (valid2? passport)
(and (valid1? passport)
(valid-byr? passport)
(valid-iyr? passport)
(valid-eyr? passport)
(valid-hgt? passport)
(valid-hcl? passport)
(valid-ecl? passport)
(valid-pid? passport)))
(define (field-in-range? pattern low high passport)
(match (regexp-match pattern passport)
[(list _ n) (number-in-range? n low high)]
[#f #f]))
(define valid-byr? (curry field-in-range? #px"byr:(\\d{4})\\b" 1920 2002))
(define valid-iyr? (curry field-in-range? #px"iyr:(\\d{4})\\b" 2010 2020))
(define valid-eyr? (curry field-in-range? #px"eyr:(\\d{4})\\b" 2020 2030))
(define (valid-hgt? passport) (or (valid-hgt-cm? passport)
(valid-hgt-in? passport)))
(define valid-hgt-cm? (curry field-in-range? #px"hgt:(\\d{2,3})cm\\b" 150 193))
(define valid-hgt-in? (curry field-in-range? #px"hgt:(\\d{2,3})in\\b" 59 76))
(define valid-hcl? (curry regexp-match? #px"hcl:#[0-9a-f]{6}\\b"))
(define valid-ecl? (curry regexp-match?
#px"ecl:(amb|blu|brn|gry|grn|hzl|oth)\\b"))
(define (valid-pid? passport)
(regexp-match? #px"pid:\\d{9}\\b" passport))
(define (number-in-range? num-str low high)
(let ([n (string->number num-str)]) (and (>= n low) (<= n high))))
(define-test-suite
tests
(test-case "validates byr"
(check-true (valid-byr? "byr:2002"))
(check-false (valid-byr? "byr:2003")))
(test-case "validates hgt"
(check-true (valid-hgt? "hgt:60in"))
(check-true (valid-hgt? "hgt:190cm"))
(check-false (valid-hgt? "hgt:190in"))
(check-false (valid-hgt? "hgt:190")))
(test-case "validates hcl"
(check-true (valid-hcl? "hcl:#123abc"))
(check-false (valid-hcl? "hcl:#123abz"))
(check-false (valid-hcl? "hcl:123abc")))
(test-case "validates ecl"
(check-true (valid-ecl? "ecl:brn"))
(check-false (valid-ecl? "ecl:wat")))
(test-case "validates pid"
(check-true (valid-pid? "pid:000000001"))
(check-false (valid-pid? "pid:0123456789"))))