aboutsummaryrefslogtreecommitdiffstats
path: root/day10/solution.nim
diff options
context:
space:
mode:
Diffstat (limited to 'day10/solution.nim')
-rw-r--r--day10/solution.nim70
1 files changed, 70 insertions, 0 deletions
diff --git a/day10/solution.nim b/day10/solution.nim
new file mode 100644
index 0000000..4277696
--- /dev/null
+++ b/day10/solution.nim
@@ -0,0 +1,70 @@
1import strutils
2import sequtils
3import sugar
4
5type
6 Instruction = tuple
7 opcode: string
8 arg: int
9
10 Program = seq[Instruction]
11
12func instructionFromString(str: string): Instruction =
13 let tokens = str.split()
14 let opcode = tokens[0]
15 var arg: int
16 if tokens.len() > 1:
17 arg = tokens[1].parseInt()
18 else:
19 arg = 0
20
21 (opcode, arg)
22
23func parseProgram(content: seq[string]): Program =
24 result = map(
25 content,
26 (line) => instructionFromString(line)
27 )
28
29proc checkSignal(cycle: int, x: int): int =
30 # cycle+1 because cycle is supposed to be starting at 0
31 if cycle+1 in [20, 60, 100, 140, 180, 220]:
32 result = x * (cycle+1)
33
34var CRT: array[0 .. 5, array[0 .. 39, char]]
35proc draw(cycle: int, x: int): void =
36 let
37 col = cycle mod 40
38 row = cycle div 40
39 if col in [x-1, x, x+1]:
40 CRT[row][col] = '#'
41
42proc execute(program: Program): int =
43 var
44 x = 1
45 cycle = 0
46
47 for i, instr in program:
48 result += checkSignal(cycle, x)
49 draw(cycle, x)
50 case instr.opcode:
51 of "addx":
52 result += checkSignal(cycle+1, x)
53 draw(cycle+1, x)
54 x += instr.arg
55 cycle += 2
56 of "noop":
57 cycle += 1
58 else:
59 assert(false)
60
61let content = readFile("./input.txt").strip().splitLines()
62let program = parseProgram(content)
63
64for row in 0 ..< 6:
65 for col in 0 ..< 40:
66 CRT[row][col] = ' '
67
68echo execute(program)
69for row in CRT:
70 echo row.join()