-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.go
105 lines (90 loc) · 2.92 KB
/
part2.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
package main
import (
"strings"
"strconv"
"bufio"
"queue"
"sort"
"fmt"
"os"
)
type Monkey struct {
Op byte
items queue.Queue
OpNum, TestNum, TrueMonkey, FalseMonkey int
}
/* Including this if the monkey divisors are not always prime, but it makes the program slower
func gcd(a, b int) int {
for b != 0 { a, b = b, a%b }
return a
}
*/
func main() {
monkeys := []Monkey{}
cMonkey := new(Monkey)
lcm := 1
fp, err := os.Open("./input.txt")
if (err != nil) { panic(err) }
defer fp.Close()
scanner := bufio.NewScanner(fp)
for scanner.Scan() {
line := scanner.Text()
if (len(line) == 0) {
monkeys = append(monkeys, *cMonkey)
} else {
switch (line[8]) {
case 'n':
for _, item := range strings.Split(line[18:], ", ") {
item, _ := strconv.Atoi(item)
cMonkey.items.Add(item)
}
case 'i':
cMonkey.OpNum, err = strconv.Atoi(line[25:])
if (err != nil) {
switch (line[23]) {
case 42: // *
cMonkey.Op = 94 // ^
case 43: // +
cMonkey.Op = 42 // *
}
cMonkey.OpNum = 2
} else { cMonkey.Op = line[23] }
case 'd':
cMonkey.TestNum, _ = strconv.Atoi(line[21:])
lcm *= cMonkey.TestNum// / gcd(lcm, cMonkey.TestNum)
case 'r':
cMonkey.TrueMonkey = int(line[29] - 48)
case 'a':
cMonkey.FalseMonkey = int(line[30] - 48)
default:
cMonkey.items = *queue.New()
}
}
}
monkeys = append(monkeys, *cMonkey)
monkeyActivity := make([]int, len(monkeys))
for x := 0; x < 10000; x++ {
for i := range monkeys {
for y := monkeys[i].items.Length(); y > 0; y-- {
monkeyActivity[i]++
item, _ := monkeys[i].items.Peek().(int)
monkeys[i].items.Remove()
switch (monkeys[i].Op) {
case 94: // ^
for z := 1; z < monkeys[i].OpNum; z++ { item *= item }
case 42: // *
item *= monkeys[i].OpNum
case 43: // +
item += monkeys[i].OpNum
}
if (item % monkeys[i].TestNum == 0) {
monkeys[monkeys[i].TrueMonkey].items.Add(item % lcm)
} else {
monkeys[monkeys[i].FalseMonkey].items.Add(item % lcm)
}
}
}
}
sort.Sort(sort.Reverse(sort.IntSlice(monkeyActivity)))
fmt.Println(monkeyActivity[0] * monkeyActivity[1])
}