aboutsummaryrefslogtreecommitdiffstats
path: root/day21/solution.nim
diff options
context:
space:
mode:
authorAn0nSaiko <porfeas12@gmail.com>2022-12-23 01:40:09 +0200
committerAn0nSaiko <porfeas12@gmail.com>2022-12-23 01:40:09 +0200
commit329ddafc220cbe6ce8cb8661574bc4b2a000530e (patch)
treeabe14eb4391d2aa5fbfedc910d3fc08233a0d27c /day21/solution.nim
parentDay 18 (diff)
downloadaoc22-329ddafc220cbe6ce8cb8661574bc4b2a000530e.tar.gz
aoc22-329ddafc220cbe6ce8cb8661574bc4b2a000530e.zip
Day 21 (part1)
Diffstat (limited to 'day21/solution.nim')
-rw-r--r--day21/solution.nim66
1 files changed, 66 insertions, 0 deletions
diff --git a/day21/solution.nim b/day21/solution.nim
new file mode 100644
index 0000000..bbf77bd
--- /dev/null
+++ b/day21/solution.nim
@@ -0,0 +1,66 @@
1import strutils
2import sequtils
3import tables
4import strformat
5
6type
7 Node = ref object of RootObj
8 left, right: string
9 val: int
10
11 AddNode = ref object of Node
12 SubNode = ref object of Node
13 MulNode = ref object of Node
14 DivNode = ref object of Node
15
16var nodes: Table[string, Node]
17
18method calc(node: Node): int =
19 node.val
20
21method calc(node: AddNode): int =
22 nodes[node.left].calc() + nodes[node.right].calc()
23
24method calc(node: SubNode): int =
25 nodes[node.left].calc() - nodes[node.right].calc()
26
27method calc(node: MulNode): int =
28 nodes[node.left].calc() * nodes[node.right].calc()
29
30method calc(node: DivNode): int =
31 nodes[node.left].calc() div nodes[node.right].calc()
32
33proc `$`(node: Node): string =
34 fmt"val: {node.val}, left: {node.left}, right: {node.right}"
35
36proc parseLine(line: string): void =
37 let tokens = line.split(": ")
38 let id = tokens[0]
39 let ops = tokens[1].split(" ")
40
41 # if single token -> its a number
42 if ops.len() == 1:
43 nodes[id] = Node(val: ops[0].parseInt())
44 else:
45 let left = ops[0]
46 let right = ops[2]
47 case ops[1]:
48 of "+":
49 nodes[id] = AddNode(left: left, right: right)
50 of "-":
51 nodes[id] = SubNode(left: left, right: right)
52 of "*":
53 nodes[id] = MulNode(left: left, right: right)
54 of "/":
55 nodes[id] = DivNode(left: left, right: right)
56 else:
57 assert(false)
58
59proc parseFile(): void =
60 let lines = readFile("./input.txt").strip().splitLines()
61
62 for line in lines:
63 parseLine(line)
64
65parseFile()
66echo nodes["root"].calc()