-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (101 loc) · 1.95 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
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
package main
import (
"fmt"
"io"
"os"
"strconv"
"github.com/devries/advent_of_code_2022/utils"
"github.com/spf13/pflag"
)
const inputfile = "../inputs/day13.txt"
func main() {
pflag.Parse()
f, err := os.Open(inputfile)
utils.Check(err, "error opening input")
defer f.Close()
r := solve(f)
fmt.Println(r)
}
func solve(r io.Reader) int {
lines := utils.ReadLines(r)
idxsum := 0
for i := 0; i < len(lines); i += 3 {
pa, _ := parsePacket([]rune(lines[i]), 0)
pb, _ := parsePacket([]rune(lines[i+1]), 0)
cmp := pa.Compare(pb)
if cmp < 0 {
idxsum += i/3 + 1
}
}
return idxsum
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
type Item interface {
Compare(Item) int
}
type PacketList []Item
type PacketNumber int
func (a PacketList) Compare(b Item) int {
switch v := b.(type) {
case PacketList:
// Comparing list to list
for i := 0; i < min(len(a), len(v)); i++ {
c := a[i].Compare(v[i])
if c != 0 {
return c
}
}
return len(a) - len(v)
case PacketNumber:
// Comparing list to number
bl := PacketList{b}
return a.Compare(bl)
default:
panic("this line should not be reachable")
}
}
func (a PacketNumber) Compare(b Item) int {
switch v := b.(type) {
case PacketList:
// Comparing number to list
al := PacketList{a}
return al.Compare(b)
case PacketNumber:
// Comparing number to number
return int(a - v)
default:
panic("this line should not be reachable")
}
}
func parsePacket(chars []rune, pos int) (Item, int) {
if chars[pos] == ',' {
pos++
}
c := pos
switch chars[c] {
case '[':
// This is a list
ret := PacketList{}
var el Item
c++
for chars[c] != ']' {
el, c = parsePacket(chars, c)
ret = append(ret, el)
}
return ret, c + 1
default:
// This is a number
for chars[c] != ',' && chars[c] != ']' {
c++
}
ns := string(chars[pos:c])
n, err := strconv.Atoi(ns)
utils.Check(err, "Unable to convert %s to integer", ns)
return PacketNumber(n), c
}
}