Advent of Code 2022 - Day 10: Cathode-Ray Tube Solution
A creative challengePart 1
Straightforward implementation, just do as the instructions
Extract
executeCycle
function for better readabilityImplementation
1const fs = require("fs")23const readData = () => {4 const data = fs5 .readFileSync("./input", "utf-8")6 .split(/\r?\n/)7 .map(row => row.split(" "))89 return data10}1112const main = () => {13 const data = readData()1415 let cycle = 116 let x = 117 let res = 018 let cycleToCheck = 201920 const executeCycle = () => {21 if (cycle === cycleToCheck) {22 res += cycle * x23 cycleToCheck += cycleToCheck === 220 ? -cycleToCheck : 4024 }25 cycle++26 }2728 for (const [instruction, param] of data) {29 switch (instruction) {30 case "noop": {31 executeCycle()32 break33 }34 case "addx": {35 executeCycle()36 executeCycle()37 x += +param38 break39 }40 }41 }4243 console.log(res)44}4546main()
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")23const readData = () => {4 const data = fs5 .readFileSync("./input", "utf-8")6 .split(/\r?\n/)7 .map(row => row.split(" "))89 return data10}1112const main = () => {13 const data = readData()1415 let x = 116 let cycle = 117 let cycleToCheck = 4018 let res = []19 let crtRow = ""2021 const executeCycle = () => {22 const crtRowPixel = cycle % 40 === 0 ? 40 : cycle % 4023 const isLitPixelProducible = x <= crtRowPixel && crtRowPixel <= x + 22425 crtRow += isLitPixelProducible ? "#" : "."2627 if (cycle === cycleToCheck) {28 res.push(crtRow)29 crtRow = ""30 cycleToCheck += cycleToCheck === 240 ? -cycleToCheck : 4031 }3233 cycle++34 }3536 for (const [instruction, param] of data) {37 switch (instruction) {38 case "noop": {39 executeCycle()40 break41 }42 case "addx": {43 executeCycle()44 executeCycle()45 x += +param46 break47 }48 }49 }5051 console.log(res.join("\n"))52}5354main()
References
Comments
Loading comments...
Tags
adventofcode
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.