diff options
| author | An0nSaiko <porfeas12@gmail.com> | 2022-12-12 00:43:39 +0200 |
|---|---|---|
| committer | An0nSaiko <porfeas12@gmail.com> | 2022-12-12 00:43:39 +0200 |
| commit | 079548b237ecf351657684dd053f3e14a55ff0ea (patch) | |
| tree | 7d07c919f7e33f348c453ef5e38aec47cf999744 /day10/solution.nim | |
| parent | Day 9 (diff) | |
| download | aoc22-079548b237ecf351657684dd053f3e14a55ff0ea.tar.gz aoc22-079548b237ecf351657684dd053f3e14a55ff0ea.zip | |
Day 11
Diffstat (limited to 'day10/solution.nim')
| -rw-r--r-- | day10/solution.nim | 70 |
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 @@ | |||
| 1 | import strutils | ||
| 2 | import sequtils | ||
| 3 | import sugar | ||
| 4 | |||
| 5 | type | ||
| 6 | Instruction = tuple | ||
| 7 | opcode: string | ||
| 8 | arg: int | ||
| 9 | |||
| 10 | Program = seq[Instruction] | ||
| 11 | |||
| 12 | func 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 | |||
| 23 | func parseProgram(content: seq[string]): Program = | ||
| 24 | result = map( | ||
| 25 | content, | ||
| 26 | (line) => instructionFromString(line) | ||
| 27 | ) | ||
| 28 | |||
| 29 | proc 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 | |||
| 34 | var CRT: array[0 .. 5, array[0 .. 39, char]] | ||
| 35 | proc 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 | |||
| 42 | proc 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 | |||
| 61 | let content = readFile("./input.txt").strip().splitLines() | ||
| 62 | let program = parseProgram(content) | ||
| 63 | |||
| 64 | for row in 0 ..< 6: | ||
| 65 | for col in 0 ..< 40: | ||
| 66 | CRT[row][col] = ' ' | ||
| 67 | |||
| 68 | echo execute(program) | ||
| 69 | for row in CRT: | ||
| 70 | echo row.join() | ||
