-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13.go
120 lines (111 loc) · 2.26 KB
/
13.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
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
type item interface {
compare(with item) int
}
type number int
func (n number) compare(i item) int {
if nitem, ok := i.(number); ok {
if n < nitem {
return -1
}
if n > nitem {
return 1
}
return 0
}
if litem, ok := i.(list); ok {
return n.toList().compare(litem)
}
panic("unexpected value in compare")
}
func (n number) toList() list {
return list([]item{number(n)})
}
type list []item
func (l list) compare(i item) int {
if n, ok := i.(number); ok {
return l.compare(n.toList())
}
litem, _ := i.(list)
for j, v := range l {
if j >= len(litem) {
return 1
}
vresult := v.compare(litem[j])
if vresult != 0 {
return vresult
}
}
if len(litem) > len(l) {
return -1
}
return 0
}
func parse(input string, pos int) (item, int) {
if input[pos] >= '0' && input[pos] <= '9' {
ss := ""
for ; pos < len(input) && input[pos] >= '0' && input[pos] <= '9'; pos++ {
ss = ss + string(input[pos])
}
n, _ := strconv.ParseInt(ss, 0, 0)
return number(int(n)), pos
}
if input[pos] == '[' {
result := list([]item{})
if input[pos+1] == ']' {
return result, pos + 2
}
for pos += 1; pos < len(input); {
var it item
it, pos = parse(input, pos)
result = append(result, it)
if input[pos] == ',' {
pos += 1
continue
}
if input[pos] == ']' {
pos += 1
break
}
}
return result, pos
}
panic(fmt.Sprintf("unexpected symbol %c at pos %d in %s", input[pos], pos, input))
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
n1, packets := 0, []item{}
for idx := 1; scanner.Scan(); idx++ {
p1, _ := parse(scanner.Text(), 0)
scanner.Scan()
p2, _ := parse(scanner.Text(), 0)
scanner.Scan()
if p1.compare(p2) < 0 {
n1 += idx
}
packets = append(packets, p1)
packets = append(packets, p2)
}
divider := func(n int) list {
return list([]item{list([]item{number(n)})})
}
packets = append(packets, divider(2))
packets = append(packets, divider(6))
sort.Slice(packets, func(i, j int) bool {
return packets[i].compare(packets[j]) < 0
})
n2 := 1
for i := 0; i < len(packets); i++ {
if ll, ok := packets[i].(list); ok && (ll.compare(divider(2)) == 0 || ll.compare(divider(6)) == 0) {
n2 *= i + 1
}
}
fmt.Println(n1, n2)
}