Advent of Code 2022 - Day 10: Cathode-Ray Tube Solution

A creative challenge

Part 1

Straightforward implementation, just do as the instructions

Extract executeCycle function for better readability

Implementation

1const fs = require("fs")
2
3const readData = () => {
4 const data = fs
5 .readFileSync("./input", "utf-8")
6 .split(/\r?\n/)
7 .map(row => row.split(" "))
8
9 return data
10}
11
12const main = () => {
13 const data = readData()
14
15 let cycle = 1
16 let x = 1
17 let res = 0
18 let cycleToCheck = 20
19
20 const executeCycle = () => {
21 if (cycle === cycleToCheck) {
22 res += cycle * x
23 cycleToCheck += cycleToCheck === 220 ? -cycleToCheck : 40
24 }
25 cycle++
26 }
27
28 for (const [instruction, param] of data) {
29 switch (instruction) {
30 case "noop": {
31 executeCycle()
32 break
33 }
34 case "addx": {
35 executeCycle()
36 executeCycle()
37 x += +param
38 break
39 }
40 }
41 }
42
43 console.log(res)
44}
45
46main()

Part 2

Update initial cycleToCheck to 40

Be careful about index manipulation

1// eg.
2const crtRowPixel = cycle % 40 === 0 ? 40 : cycle % 40

Implementation

1const fs = require("fs")
2
3const readData = () => {
4 const data = fs
5 .readFileSync("./input", "utf-8")
6 .split(/\r?\n/)
7 .map(row => row.split(" "))
8
9 return data
10}
11
12const main = () => {
13 const data = readData()
14
15 let x = 1
16 let cycle = 1
17 let cycleToCheck = 40
18 let res = []
19 let crtRow = ""
20
21 const executeCycle = () => {
22 const crtRowPixel = cycle % 40 === 0 ? 40 : cycle % 40
23 const isLitPixelProducible = x <= crtRowPixel && crtRowPixel <= x + 2
24
25 crtRow += isLitPixelProducible ? "#" : "."
26
27 if (cycle === cycleToCheck) {
28 res.push(crtRow)
29 crtRow = ""
30 cycleToCheck += cycleToCheck === 240 ? -cycleToCheck : 40
31 }
32
33 cycle++
34 }
35
36 for (const [instruction, param] of data) {
37 switch (instruction) {
38 case "noop": {
39 executeCycle()
40 break
41 }
42 case "addx": {
43 executeCycle()
44 executeCycle()
45 x += +param
46 break
47 }
48 }
49 }
50
51 console.log(res.join("\n"))
52}
53
54main()

References

Original problem

Comments

Loading comments...

Tags

adventofcode

Next Post

Advent of Code 2022 - Day 11: Monkey in the Middle

Math and modulo operation

Previous Post

HoningJS

Search Posts