-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04.go
134 lines (120 loc) · 2.26 KB
/
04.go
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"bufio"
"log"
"os"
"regexp"
"strconv"
"strings"
)
type Validator func(string) bool
func inRange(from, to int) Validator {
return func(s string) bool {
if val, err := strconv.Atoi(s); err == nil {
return from <= val && to >= val
}
return false
}
}
func hasPattern(exp string) Validator {
re := regexp.MustCompile(exp)
return func(s string) bool {
return re.Match([]byte(s))
}
}
func const_(x bool) Validator {
return func(s string) bool { return x }
}
func or(xs ...Validator) Validator {
return func(s string) bool {
for _, x := range xs {
if x(s) {
return true
}
}
return false
}
}
var validators = map[string]Validator{
"byr": inRange(1920, 2002),
"iyr": inRange(2010, 2020),
"eyr": inRange(2020, 2030),
"hgt": or(
hasPattern("(1[5-8][0-9]|19[0-3])cm"),
hasPattern("(59|6[0-9]|7[0-6])in"),
),
"hcl": hasPattern("#[0-9a-f]{6}"),
"ecl": hasPattern("(amb|blu|brn|gry|grn|hzl|oth)"),
"pid": hasPattern("[0-9]{9}"),
"cid": const_(true),
}
type Empty struct{}
type Set map[string]Empty
func NewSet(xs []string) Set {
var e Empty
s := make(Set)
for _, x := range xs {
s[x] = e
}
return s
}
func (s1 Set) isSubset(s2 Set) bool {
for k, _ := range s1 {
if _, ok := s2[k]; !ok {
return false
}
}
return true
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
spec := NewSet([]string{
"byr",
"iyr",
"eyr",
"hgt",
"hcl",
"ecl",
"pid",
})
validCount := 0
validCount2 := 0
fieldVals := make(map[string]string, 0)
nextPassport := func() {
isValid := true
fields := make([]string, len(fieldVals))
for f, v := range fieldVals {
fields = append(fields, f)
if validator, ok := validators[f]; !(ok && validator(v)) {
isValid = false
}
}
if spec.isSubset(NewSet(fields)) {
validCount++
} else {
isValid = false
}
if isValid {
validCount2++
}
fieldVals = make(map[string]string)
}
for {
if !scanner.Scan() {
nextPassport()
break
}
rawFields := strings.Fields(scanner.Text())
if len(rawFields) == 0 {
nextPassport()
continue
}
for _, rawField := range rawFields {
parsed := strings.Split(rawField, ":")
field, val := parsed[0], parsed[1]
fieldVals[field] = val
}
}
log.Println(validCount)
log.Println(validCount2 - 1)
}