-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathd02.go
More file actions
72 lines (56 loc) · 1.37 KB
/
d02.go
File metadata and controls
72 lines (56 loc) · 1.37 KB
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
package d02
import (
"regexp"
"strconv"
"strings"
"com.github/augustoccesar/adventofcode/golang/structure"
)
var pattern = regexp.MustCompile(`(\d{1,2})-(\d{1,2})\s(\w{1}):\s(\w*)`)
type Day02 struct{}
func (d *Day02) Year() int { return 2020 }
func (d *Day02) Day() int { return 2 }
func (d *Day02) PartOne() string {
valid := 0
rows := strings.Split(structure.ReadDefaultInput(d), "\n")
for _, row := range rows {
match := pattern.FindAllStringSubmatch(row, -1)[0]
min, err := strconv.Atoi(match[1])
if err != nil {
panic(err)
}
max, err := strconv.Atoi(match[2])
if err != nil {
panic(err)
}
char := match[3]
password := match[4]
charInstances := strings.Count(password, char)
if charInstances >= min && charInstances <= max {
valid++
}
}
return strconv.Itoa(valid)
}
func (d *Day02) PartTwo() string {
valid := 0
rows := strings.Split(structure.ReadDefaultInput(d), "\n")
for _, row := range rows {
match := pattern.FindAllStringSubmatch(row, -1)[0]
idx1, err := strconv.Atoi(match[1])
if err != nil {
panic(err)
}
idx1--
idx2, err := strconv.Atoi(match[2])
if err != nil {
panic(err)
}
idx2--
char := []rune(match[3])[0]
password := []rune(match[4])
if (password[idx1] == char && password[idx2] != char) || (password[idx1] != char && password[idx2] == char) {
valid++
}
}
return strconv.Itoa(valid)
}