-
Notifications
You must be signed in to change notification settings - Fork 0
/
day2.go
57 lines (46 loc) · 1.46 KB
/
day2.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
package day2
import (
"fmt"
"regexp"
"strconv"
"strings"
)
var passwordLine = regexp.MustCompile(`^(\d+)-(\d+) ([a-z]): ([a-z]+)$`)
type validationFunc func(char uint8, tok1, tok2 int, password string) bool
func Part1(passwordLines []string) (int, error) {
return validPasswords(passwordLines, validLetterCount)
}
func Part2(passwordLines []string) (int, error) {
return validPasswords(passwordLines, oneOccurrenceInPositions)
}
func validPasswords(passwordLines []string, validFunc validationFunc) (int, error) {
var validCount int
for _, l := range passwordLines {
matches := passwordLine.FindStringSubmatch(l)
if matches == nil {
return 0, fmt.Errorf("day2: couldn't parse input line %q", l)
}
tok1, err := strconv.Atoi(matches[1])
if err != nil {
return 0, fmt.Errorf("day2: parsing first token in %q: %w", l, err)
}
tok2, err := strconv.Atoi(matches[2])
if err != nil {
return 0, fmt.Errorf("day2: parsing second token in %q: %w", l, err)
}
char, password := matches[3][0], matches[4]
if validFunc(char, tok1, tok2, password) {
validCount++
}
}
return validCount, nil
}
func validLetterCount(char uint8, lower, upper int, password string) bool {
count := strings.Count(password, string(char))
return lower <= count && count <= upper
}
func oneOccurrenceInPositions(char uint8, i1, i2 int, password string) bool {
i1--
i2--
return (password[i1] == char && password[i2] != char) || (password[i1] != char && password[i2] == char)
}