-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03.go
80 lines (73 loc) · 1.34 KB
/
day03.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
package main
import (
"bufio"
"fmt"
"os"
)
func common(lhs, rhs string) (rune, bool) {
// Quadratic; optimize later if needed.
for _, l := range lhs {
for _, r := range rhs {
if l == r {
return l, true
}
}
}
return ' ', false
}
func common3(a, b, c string) (rune, bool) {
// ¯\_(ツ)_/¯
// We're scanning short strings. This is probably not too bad.
for _, ca := range a {
for _, cb := range b {
if ca != cb {
continue
}
for _, cc := range c {
if cc == ca {
return cc, true
}
}
}
}
return ' ', false
}
func prio(c rune) int {
if c >= 'a' && c <= 'z' {
return int(c-'a') + 1
}
return int(c-'A') + 27
}
func part1(rucksacks []string) int {
total := 0
for _, line := range rucksacks {
n := len(line)
lhs, rhs := line[:n/2], line[n/2:]
c, ok := common(lhs, rhs)
if !ok {
continue
}
total += prio(c)
}
return total
}
func part2(rucksacks []string) int {
total := 0
for i := 0; i < len(rucksacks); i += 3 {
c, ok := common3(rucksacks[i], rucksacks[i+1], rucksacks[i+2])
if !ok {
continue
}
total += prio(c)
}
return total
}
func main() {
rucksacks := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
rucksacks = append(rucksacks, scanner.Text())
}
fmt.Printf("Part1: %d\n", part1(rucksacks))
fmt.Printf("Part2: %d\n", part2(rucksacks))
}