-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.go
97 lines (86 loc) · 1.8 KB
/
18.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"strings"
)
func openLayer(N *int, values []int, ops []byte) {
*N = *N + 1
values[*N] = 0
ops[*N] = '+'
}
func closeLayer(N *int, values []int, ops []byte) {
values[*N-1] = applyOp(ops[*N-1], values[*N-1], values[*N])
*N = *N - 1
}
func applyOp(op byte, a int, b int) (res int) {
switch op {
case '+':
res = a + b
case '*':
res = a * b
default:
log.Fatalf("Unexpected operator: %d", op)
}
return
}
const STACKSIZE = 100
func main() {
var fileName string
var version2 bool
flag.StringVar(&fileName, "file", "data/in18.txt", "Input file to use")
flag.BoolVar(&version2, "v2", false, "Use task2 version")
flag.Parse()
content, err := ioutil.ReadFile(fileName)
if err != nil {
log.Fatal(err)
}
var values [STACKSIZE]int
var ops [STACKSIZE]byte
totalSum := 0
lines := strings.Split(strings.ReplaceAll(string(content), " ", ""), "\n")
for _, line := range lines {
N := 0
ops[N] = '+'
values[N] = 0
rd := strings.NewReader(line)
for rd.Len() > 0 {
char, _ := rd.ReadByte()
switch char {
case '(':
openLayer(&N, values[:], ops[:])
case ')':
closeLayer(&N, values[:], ops[:])
for version2 && ops[N] == '*' {
closeLayer(&N, values[:], ops[:])
}
case '+':
ops[N] = char
case '*':
ops[N] = char
if version2 {
openLayer(&N, values[:], ops[:])
}
default:
rd.UnreadByte()
var val int
_, err := fmt.Fscanf(rd, "%d", &val)
if err != nil {
log.Fatalf("Unexpected parsing error!")
}
values[N] = applyOp(ops[N], values[N], val)
}
}
if version2 {
for N > 0 {
closeLayer(&N, values[:], ops[:])
}
} else if N != 0 {
log.Fatal("Unexpected end depth:", N)
}
totalSum += values[N]
}
fmt.Println("Computed sum of results:", totalSum)
}