diff options
| author | An0nSaiko <porfeas12@gmail.com> | 2022-12-23 01:40:09 +0200 |
|---|---|---|
| committer | An0nSaiko <porfeas12@gmail.com> | 2022-12-23 01:40:09 +0200 |
| commit | 329ddafc220cbe6ce8cb8661574bc4b2a000530e (patch) | |
| tree | abe14eb4391d2aa5fbfedc910d3fc08233a0d27c /day21/solution.nim | |
| parent | Day 18 (diff) | |
| download | aoc22-329ddafc220cbe6ce8cb8661574bc4b2a000530e.tar.gz aoc22-329ddafc220cbe6ce8cb8661574bc4b2a000530e.zip | |
Day 21 (part1)
Diffstat (limited to 'day21/solution.nim')
| -rw-r--r-- | day21/solution.nim | 66 |
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 @@ | |||
| 1 | import strutils | ||
| 2 | import sequtils | ||
| 3 | import tables | ||
| 4 | import strformat | ||
| 5 | |||
| 6 | type | ||
| 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 | |||
| 16 | var nodes: Table[string, Node] | ||
| 17 | |||
| 18 | method calc(node: Node): int = | ||
| 19 | node.val | ||
| 20 | |||
| 21 | method calc(node: AddNode): int = | ||
| 22 | nodes[node.left].calc() + nodes[node.right].calc() | ||
| 23 | |||
| 24 | method calc(node: SubNode): int = | ||
| 25 | nodes[node.left].calc() - nodes[node.right].calc() | ||
| 26 | |||
| 27 | method calc(node: MulNode): int = | ||
| 28 | nodes[node.left].calc() * nodes[node.right].calc() | ||
| 29 | |||
| 30 | method calc(node: DivNode): int = | ||
| 31 | nodes[node.left].calc() div nodes[node.right].calc() | ||
| 32 | |||
| 33 | proc `$`(node: Node): string = | ||
| 34 | fmt"val: {node.val}, left: {node.left}, right: {node.right}" | ||
| 35 | |||
| 36 | proc 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 | |||
| 59 | proc parseFile(): void = | ||
| 60 | let lines = readFile("./input.txt").strip().splitLines() | ||
| 61 | |||
| 62 | for line in lines: | ||
| 63 | parseLine(line) | ||
| 64 | |||
| 65 | parseFile() | ||
| 66 | echo nodes["root"].calc() | ||
