-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
62 lines (52 loc) · 1.19 KB
/
main.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
package main
import (
input "aoc2020/inpututils"
"fmt"
"regexp"
"strings"
"strconv"
)
func main(){
fmt.Println("--- Part One ---")
fmt.Println(Part1("input.txt"))
fmt.Println("--- Part Two ---")
fmt.Println(Part2("input.txt"))
}
func Part1(filename string) int {
lines := input.ReadLines(filename)
validPasswords := 0
for _, line := range(lines){
min, max, letter, pword := getParts(line)
letterCount := strings.Count(pword, letter)
if min <= letterCount && letterCount <= max {
validPasswords += 1
}
}
return validPasswords
}
func Part2(filename string) int {
lines := input.ReadLines(filename)
validPasswords := 0
for _, line := range(lines){
pos1, pos2, letter, pword := getParts(line)
if (string(pword[pos1 - 1]) == letter) != (string(pword[pos2 - 1]) == letter) {
validPasswords += 1
}
}
return validPasswords
}
func getParts(line string) (int, int, string, string) {
re := regexp.MustCompile(`(\d+)-(\d+) ([a-z]): ([a-z]+)`)
parts := re.FindStringSubmatch(line)
return toInt(parts[1]), toInt(parts[2]), parts[3], parts[4]
}
func check(err error) {
if err != nil {
panic(err)
}
}
func toInt(s string) int {
i, err := strconv.Atoi(s)
check(err)
return i
}