-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
129 lines (106 loc) · 2.21 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
123
124
125
126
127
128
129
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/devries/advent_of_code_2022/utils"
"github.com/spf13/pflag"
)
const inputfile = "../inputs/day21.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) int64 {
lines := utils.ReadLines(r)
monkeys := make(map[string]Job)
for _, ln := range lines {
name, j := parseLine(ln)
monkeys[name] = j
}
rpnList := []string{"root"}
// Expand out
keepGoing := true
for keepGoing {
// Do this until there are no more monkey names in stack
keepGoing = false
newList := []string{}
// Move from bottom to top
for _, m := range rpnList {
if strings.ContainsAny(m, "0123456789+-/*") {
newList = append(newList, m)
continue
}
// Split the operation op and append this operation to the existing op stack
keepGoing = true
j := monkeys[m]
switch j.Operation {
case "":
newList = append(newList, j.A)
default:
newList = append(newList, j.B, j.A, j.Operation)
}
}
rpnList = newList
}
// Do calculation
nStack := IntStack{}
for _, v := range rpnList {
switch v {
case "+":
a := nStack.Pop()
b := nStack.Pop()
nStack.Push(a + b)
case "-":
a := nStack.Pop()
b := nStack.Pop()
nStack.Push(a - b)
case "/":
a := nStack.Pop()
b := nStack.Pop()
nStack.Push(a / b)
case "*":
a := nStack.Pop()
b := nStack.Pop()
nStack.Push(a * b)
default:
n, err := strconv.ParseInt(v, 10, 64)
utils.Check(err, "unable to convert %s to integer", v)
nStack.Push(n)
}
}
return nStack[0]
}
type Job struct {
A string
B string
Operation string
}
func parseLine(ln string) (string, Job) {
components := strings.Split(ln, ": ")
jobParts := strings.Fields(components[1])
switch len(jobParts) {
case 1:
job := Job{jobParts[0], "", ""}
return components[0], job
default:
job := Job{jobParts[0], jobParts[2], jobParts[1]}
return components[0], job
}
}
type IntStack []int64
func (s *IntStack) Pop() int64 {
idx := len(*s) - 1
r := (*s)[idx]
*s = (*s)[:idx]
return r
}
func (s *IntStack) Push(n int64) {
*s = append(*s, n)
}