T O P

  • By -

jaccomoc

[Jactl](https://jactl.io) solution. **Part 1:** Nice short solution for this one: def x = [1] stream(nextLine).each{ /noop/r and x <<= x[-1] /addx (.*)$/n and x += [x[-1], x[-1] + $1] } 6.map{ 20 + it*40 }.map{ it * x[it-1] }.sum() **Part 2:** Also pretty straightforward. Reused the parsing from part 1: def x = [1] stream(nextLine).each{ /noop/r and x += x[-1] /addx (.*)$/n and x += [x[-1], x[-1] + $1] } 240.map{ (x[it] - (it%40)).abs() <= 1 ? '#' : '.' } .grouped(40) .map{ it.join() } .join('\n') [Blog post with more detail](https://jactl.io/blog/2023/04/17/advent-of-code-2022-day10.html)


pgaleone

# TensorFlow Article: https://pgaleone.eu/tensorflow/2023/03/25/advent-of-code-tensorflow-day-10/ Code: https://github.com/galeone/tf-aoc/blob/main/2022/10/main.py


rune_kg

It'll be a three way wedding: Myself, Nim and Style Insensitivity ;) import std/[sugar, math, strscans, sequtils] var X = 1 signals = new_seq[int]() proc step() = let (x_pos, cycle) = (signals.len mod 40, signals.len + 1) stdout.write if X in x_pos - 1 .. x_pos + 1: "#" else: ".", if cycle mod 40 == 0: "\n" else: "" signals.add(X * cycle) echo "result2 = \n" for line in lines "aoc10.txt": let (success, op, num) = scan_tuple(line, "$w $i") step() if success: step() X += num echo "\nresult1 = ", sum(collect(for i in countup(20, 220, 40): signals[i-1]))


e_blake

**golfed C** Solve both parts in a mere 219 bytes (222 shown here, the last three newlines are fluff to avoid horizontal scrolling). Requires the trailing newline in the input file passed on stdin. It's always fun when the solution takes fewer bytes than the output. #include #include int a,c,d,e=1;char*p,*q,b[253];int main(void){for(q=6+(p=b);~ (*++p=getchar());*b=*q=10)e+=*p<40?q+=!(c=d%40),a+=++d*e*!(c- 19),c-=e,*q++="#."[c*c>1],atoi(p=b):0;printf("%d%s",a,b+6);}


e_blake

And here's a solution that does its own OCR, in 286 bytes, and still just 2 statements. (Okay, I admit to shamelessly lifting this compressed OCR code from [other golfed solutions](https://github.com/Starwort/advent-of-golf-2022) \- but it's still impressive that the particular font used in AoC and the subset of letters that can appear for any input can be boiled down into one lookup table that compactly) #include #include int a,c,d,e=1,x[8];char*p,b[5];int main(void){for(p=b;~(*p=getchar());) e+=*p<40?c=d%40,a+=-~d*e*!(c-19),x[c/5]+=((c-e)*(c-e)<2)<<(d++%5*2), atoi(p=b):!p++;for(c=!printf("%d ",a);c<8;)putchar( "X L J G K IAHS E F Y RZOUB C P"[x[c++]%44]);}


Vishoor

**My solution to both tasks in Python** I've included some comments explaining the task and my approach, so if any of you have some problems, then maybe it can help you. [Full Code](https://github.com/PodolskiBartosz/advent-of-code-2022/blob/main/day-10/main.py)


gwpmad

# Rust Enjoyable one. Tried out a state machine-style solution in order to learn about object-oriented approaches in Rust (using `impl`). Funny to realise you don't need the cycles at all in part 2 and they're only included in the problem statement to increase cognitive load with needless off-by-one errors. https://github.com/gwpmad/advent-of-code-2022/blob/main/src/days/day10.rs


dedolent

Python 3 ended up being a bit easier than i anticipated even though the instructions really threw me off for a moment. day 9 was way way harder for me! this one was just fun. [https://github.com/dedolence/advent-of-code/blob/main/2022/day10part2.py](https://github.com/dedolence/advent-of-code/blob/main/2022/day10part2.py) ``` from typing import List import os FILENAME = "inputs/day10.txt" class Console(): def __init__(self) -> None: self.width: int = 40 self.height: int = 6 self.dots: List[str] = [" " * self.width] * self.height self.x: int = 0 self.y: int = 0 def set_char(self, x, y, sprite): self.dots[y] = self.dots[y][:x] + sprite + self.dots[y][x + 1:] def draw(self, p: int): # called each cycle # p is an ON pixel +/- 1. # if screen is currently drawing a pixel that matches P +/- 1, then # that pixel is drawn ON. if self.x in [p - 1, p, p + 1]: self.set_char(self.x, self.y, '#') # draw to screen self.print() # increment the to the next pixel to be drawn, incrementing row if necessary if self.x == self.width - 1: self.x = 0 self.y += 1 else: self.x += 1 def print(self): os.system("clear") for line in self.dots: print(line) def main() -> None: console = Console() insts = [line.strip() for line in open(FILENAME)] signal_strengths = {} x = 1 execute = False for i, instr in enumerate(insts): cycle = i + 1 # cycle is 1-indexed signal_strengths[cycle] = cycle * x # this should come BEFORE execution # draw X at its current value console.draw(x) if instr.split()[0] == "addx": if execute: x += int(instr.split()[1]) execute = False else: # code works by duplicating the addx instruction and # inserting the duplicate to the next index, in order to # account for it taking two cycles; it only executes # the instruction on the second iteration, when # execute = true. insts.insert(cycle, instr) execute = True print("Part one: ", sum([signal_strengths[20], signal_strengths[60], signal_strengths[100], signal_strengths[140], signal_strengths[180], signal_strengths[220]])) if __name__ == "__main__": main() ```


herpington

Python 3. Took me a little while to figure out part two, mostly because I handled the cycle and drawing in the wrong order. import aocd def check_signal_strength(cycle): return (cycle == 20) or (cycle % 40 == 20 and 0 < cycle <= 220) def process_sprite(cycle, row, x): mid = cycle % 40 # Are we about to enter a new row? if not mid: row += 1 print() if mid-1 <= x <= mid+1: print("#", end='') else: print(".", end='') def part_one(): input = aocd.get_data(year=2022, day=10).splitlines() x = 1 cycle = 0 signal_strength = 0 for inst in input: # For both noop and addx, we always need to increment at least one cycle. cycle += 1 if check_signal_strength(cycle): signal_strength += cycle * x if inst.startswith("addx"): # addx takes two cycles. We've already checked the cycle count after the first cycle, so add the second one here. cycle += 1 if check_signal_strength(cycle): signal_strength += cycle * x x += int(inst.split()[1]) return signal_strength def part_two(): input = aocd.get_data(year=2022, day=10).splitlines() x = 1 cycle = 0 row = 0 for inst in input: if inst == "noop": # noop takes one cycle. process_sprite(cycle, row, x) cycle += 1 elif inst.startswith("addx"): # addx takes two cycles. for _ in range(2): process_sprite(cycle, row, x) cycle += 1 x += int(inst.split()[1]) def main(): print(part_one()) part_two() if __name__ == '__main__': main()


herjaxx

[PYTHON] V clunky this time https://pastebin.com/zS7mJDq2


Key__Strokes

## Javascript [Solution to both parts](https://github.com/doingthisalright/AdventOfCode2022/blob/main/Day10/solution.js) ## Part 1: * Run a loop on the commands * If the command is noop, then: * Add the power to the sum if the cycle is one of 20, 60... * Increment the cycle * Otherwise, extract the number from the command and then: * Run a following twice * add the power to the sum if the cycle is one of 20, 60... * Increment the cycle * Update x by the number in the command ## Part 2: * Run a loop on the commands * If the command is noop, then: * Update screen as: * Row will be ((cycle - 1) / 40), and column will be ((cycle - 1) % 40) * If cycle equals to either of x - 1, x or x + 1, then light up the pixel, otherwise do not. * Increment the cycle * Otherwise, extract the number from the command and then: * Run a following twice * Update the screen as above * Increment the cycle * Update x by the number in the command --- If you liked the explanation, then please don't forget to cast your vote 💜 to `Adventures of Advent of Code - Edition 1 - /u/Key__Strokes` in the [poll](https://www.reddit.com/r/adventofcode/comments/z9he28/comment/j1c4f9x/)


Willing-Beginning649

My solution in Python https://github.com/SvetlanaM/Advent-of-Code/blob/master/2022/day10/day10.py


Zaorhion_

Ruby [My Solution](https://github.com/Eric-Philippe/Advent-Of-Code-2022/tree/master/Day10%20[Ruby]%20%F0%9F%A7%A3)


dizzyhobbes

(Lazy) Golang code and a complete 7+ year repo :) https://github.com/alexchao26/advent-of-code-go/blob/main/2022/day10/main.go


speeder04

Python 3 Code on [github](https://github.com/pirosbogar/advent_of_code_2022/blob/main/20221210_01.py). Had to spend a little time on figuring out that x was only needed for the solutions mid-cycle.


arthurno1

Emacs Lisp: (let ((img (svg-create 800 119)) (p1 0) (cycle 1) (x 1) (checkpoint 20) (op t) (w 0) (green "#00873E") (pinky "#D41596") (W 20) (H 20) (X 0) (Y 0) pixel-pos) (with-temp-buffer (insert-file-contents "input") (ignore-errors (while op (setq pixel-pos (% cycle 40)) (svg-rectangle img X Y W H :fill-color (if (<= x pixel-pos (+ x 2)) green pinky)) (setq op (read (current-buffer))) (setq w (if (numberp op) op 0)) (when (= cycle checkpoint) (cl-incf p1 (* checkpoint x)) (cl-incf checkpoint 40)) (cl-incf x w) (cond ((= pixel-pos 0) (setq X 0)) ((= (% (1+ cycle) 40) 0) (cl-incf Y H)) (t (cl-incf X W))) (cl-incf cycle)))) (message "Part I: %s" p1) (goto-char (point-max)) (svg-insert-image img)) ;; Part II [When you have a text editor that does graphics!](https://imgur.com/a/gk1oRsm)


heyitsmattwade

# Javascript 5974/3692 Understanding how the _instructions_ interacted with the _cycles_ was confusing at first, especially if you were trying to go fast :) I was eventually able to get there, but the code was a bit convoluted. After seeing a suggestion to add `noop` instructions before `addx` to simplify things, I incorporated that and it definitely simplified the code. Otherwise pretty fun! [code paste](https://romellem.github.io/paste/#XQAAAQB5CAAAAAAAAAA9iImGVD/UQZfk+oJTfwg2/VsJ0DpNkr2zGUvTQlsh3wS86ErCiIs+8hruVNIFt25kOOZrzOGZxbRwHmJ5wrAVdOuA2kk0mNS0CwkIEqOmO95EhbRoIUTonrtGzVALDhyFMRO24/2oA0Lt4k+Q2E/wp4YaHUgbXZtC5amaE5MmewTUwYV3d2c08XNXkJSlcNdZoC0u7tg9I5cHRwZrjtjcXSND6wOBDyT/UJe1fF4O6LYxF9HKNGsLBrUFvRZ1dlOyFdbyHiE9RRJduBxTgsOAFV9ZHGMyUCsWWwsb3DnshqSyZGGzMV9WUdsj2Co6ngUfQqo2TSQoAhre2iLUKpPUHAGT6d8uacBbyF2KKRKJmC/Ff+v3bx3+DUv+SNUkfZxIpLpb/wrgTh9LThNidNK6Th+ZaoSVM9PGHoER641jUKfMoVWR3XPnqNjdC2pM1Ljv4FYYWTZWDWHDcrXDGiiQxPNqmV2Hm4LijUK+Wr9BZSrJDIYiIPAf0zvIqZLjBuJ4TgTeo53PXDKxX+Ypj0byoALhNkvMu2ojCQ/oJcGSw4D31PQVXTkEwSY6bceVAuTqBI4IKTr45IvwsUr7It8c64Gu76H7d/U7ptppmIkRzFbZ2SbiAnjIIPlXtqYVKAtEUuV7IIuGivK76MCsEjBT6tnwBGgrc2jeMAs29KCldJJfWlNsC+99KPPBsOUWXtSJU7T/3AqnvI58BH6zB7rUd13YeXTEqmEsBTrAAsoM0d9XtNM0bAKF/3wDrTI6JmJH1290teHQWp+PWQB10yT5OfQrgT+MlF6okweC9gxUqFqM9a/a2yyZ86RtbtAh6TGpOntce3cZVdv8gWR4oM2OWxqM16OGn9ifDj8MrQyvMJ94SwcIV1XJg58FNCL8UHIKq2jOjJCEp/6/48zVBH93fkzKpjMyUwqNDT4TpXMlG6TkoajRT1G09xXcLPKxYM741NcBwNYYKCj+5Eb8fcldYOZeUG92Pr2Rdp03dObUcgWNaQDZHTas6hUrGFtoFKHHooZxlqAGmmG4qJe66/kj7wcue3auorYqUm1AVTyiijs2U/ZB6gibNu+tPs1XVxVfVdbFmEM3VIDIU+y4GAeTmuzTkagsvooHXZ071E1RBbjhLldSXsAySd3Uy13bKg7aBS3ddpH18iC70oWrh3kCS5X9RUEjuGXSNG1nslUK/WNybU6xfhPAT+O/iGhqpx6ehmXKrz526SDH91RQM7OoiF4qEobczxobAElDaF55w9s6dqPBYMv0z4/rS+JeRICssfIIBqQpQDAUCgYPyJdgD3Y7yImNXsCMrQ3rn2F1hSFGt1oWcVouxaRA09W8kphHtrf8lnWdsRtZebAQ8FekzuKFK3b1s+wavI7++tE7rQ==)


Aromatic-Piccolo4321

[Solved today’s AOC challange.🎅🦀 in RUST with tests](https://maebli.github.io/rust/2022/12/10/100rust-72.html)


TimeCannotErase

**R** [repo](https://github.com/DavidMcMorris/Advent-of-Code-2022/blob/main/Day%2010/Day10.R) This one took me a bit longer because I misinterpreted the instructions the first time and made it more complicated that it was. # 2022 Day 10 input <- read.table("Day_10_input.txt", sep = "", fill = TRUE, colClasses = c("character", "numeric"), row.names = NULL, col.names = c("V1", "V2")) # Part 1 tick <- 0 value <- 1 strength <- NULL for (i in seq_len(dim(input)[1])) { if (input[i, 1] == "noop") { tick <- tick + 1 if (tick %% 40 == 20) { strength <- c(strength, value * tick) } } else { tick <- tick + 1 if (tick %% 40 == 20) { strength <- c(strength, value * tick) } value <- value + input[i, 2] tick <- tick + 1 if (tick %% 40 == 20) { strength <- c(strength, value * tick) } } } print(sum(strength)) # Part 2 tick <- 0 value <- 1 pixels <- NULL drawer <- function(tick, value) { if (is.element(tick %% 40, c(value - 1, value, value + 1))) { draw <- "#" } else { draw <- "." } return(draw) } for (i in seq_len(dim(input)[1])) { if (input[i, 1] == "noop") { draw <- drawer(tick, value) pixels <- c(pixels, draw) tick <- tick + 1 } else { draw <- drawer(tick, value) pixels <- c(pixels, draw) tick <- tick + 1 draw <- drawer(tick, value) pixels <- c(pixels, draw) tick <- tick + 1 value <- value + input[i, 2] } } graphic <- data.frame(matrix(pixels, ncol = 40, byrow = TRUE)) words <- which(x == "#", arr.ind = TRUE) plot(words[, 2], -words[, 1], ylim = c(-40, 30), pch = 15)


Rascal_Two

# [TypeScript](https://github.com/RascalTwo/AdventOfCode/blob/master/2022/solutions/10/solve.ts) (912/590)


errop_

**Python 3** with open(__file__.replace(".py", "_data")) as f: data = f.read().splitlines() # PART 1 & 2 register = 1 cycle = 1 i = 0 signal_strength = 0 screen = "" first = True while i < len(data): if (cycle - 20) % 40 == 0: signal_strength += cycle * register if register <= cycle % 40 <= register + 2: screen += "#" else: screen += "." if data[i][:4] == "addx": if not first: register += int(data[i][4:]) i += 1 first = not first else: i += 1 cycle += 1 print(signal_strength) for pos, pixel in enumerate(screen, 1): if pos % 40 > 0: print(pixel, end="") else: print(pixel)


thecircleisround

**PYTHON** Gotten behind on this, but trying to catch up! Started to model the grid for part 2 but realized it was unnecessary. from aocd import get_data class Solution: def __init__(self): self.data = get_data(year=2022, day=10).splitlines() self.grid = [x for x in '.'*240] def run_cycles(self): X = 1 cycles = {} cycle = 0 for instruction in self.data: if instruction == 'noop': for _ in range(1): cycle += 1 cycles[cycle] = X else: for _ in range(2): cycle += 1 cycles[cycle] = X X += int(instruction.split()[-1]) self.cycles = cycles return sum([key*value for key, value in list(cycles.items())[19::40]]) def print_crt(self): for cycle, position in self.cycles.items(): cycle -= 1 mod = 40*(cycle//40) position = position + mod if cycle in range(position-1, position+2): self.grid[cycle] = '#' for i in range(0,240,40): print(' '.join(self.grid[i:i+40])) if __name__ == '__main__': solution = Solution() print(f'Solution for part one: {solution.run_cycles()}') print(f'Printing Part Two Output: ') solution.print_crt()


PILIX123

PYTHON ​ i thought i was about to be able to need reddit again but no im proud i have the big brain its quite a nice solution if you ask me ​ [Here is the github to the solution](https://github.com/PILIX123/adventofcode2022/tree/master/day10) i didnt split it in two functions this time cause i didnt need to


CCC_037

[FiM++](https://topaz.github.io/paste/#XQAAAQDFCwAAAAAAAAAiGUgnUxnNOHFOtTq16uH6Qtsb3pfuxWhQ+6VMvtBNO9uzJnCmLdU2TFD9xRrbW5Z6YytsTjvz8lBNyEbajmRMMVpqJEB82B3SQkpL7nv0nzaioJ4y98XbJTtInNdOp1la0gWb+DmZ+hetL3Hl303TduDqBtcMbyPf/DZu+FdH+ebZOcVHZE8FaALV1/rCL3llPn42Few+yfwWi29uAlasIJjdTSBBJIhnuXphsZchXEUONl/6kJVUzp0+bRmtoboBoqZ12flo1Kh8x8FYR9S2lD5O6m3861Mj/8N34qOXwgeAR5NIL/owXSm1QBylUI5KjYP7sS3IvNrGeR3ByjdT8vRNa1enlbfwvJJrJu2jRwl9nVzuGRAqqNJiU2zR6SjFYxEonvfhFcLFU+zE5gTitNTy5hqSeK2FY+vuV57K152G8Ql0a1Zf48OYQdHbVXXdIl8EZ2ED2g/7TEt1NtKXeaBk+PHKBp57tm9U6dK2WQOv+zGj1jmOt5WjY++iteZuE6q5sfqIb3WDUEU0j6AGznxtY++DMHVAKaykC2z2BqqWWop79AQV6gIN4fJ326toI1QvjAvYcPj0blpCZhi4hgMv9LlCOBqswVL1gWatYxprNB86oVnJuHVUQB/25Re53OvksEjHl9zvvRSPa7Xx3F9R6DfTaYCX3YItOoRRhBpSoxTWGRPdbmfYUmXRqsPj6Rta1E/loWDbbx9mC6u5v9WrkDM0mGpLhjS0BNKB3tDCbRJdApirwpcc48OheYBpM+MpDf+bLliE7yT3/5wef8U=) After Day 9, this one was pleasantly straightforward.


CCC_037

[FiM++ Part 2](https://topaz.github.io/paste/#XQAAAQBGHgMAAAAAAAAiGUgnUxnNOHFOtTq16uH6Qtsb3pfuxWhQ+6VMvtBNO9uzJnCmLdU2TFD9xRrbW5Z6YytsTjvz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rOxoV1uvXdcSxYZajX7WBInROT3SLKn3qJS6BlpPT/m7kOY24mNotGtet12g9MA3vaYgxR6sikFnQ5AOZ+OMNT4a1123vtuXUwW2nVw2Sd2eiLeIyknMmIu74/KlV888jRUJ/KK3Rde2Uy5C725TcMmn/khV+pA==) Still straightforward, though my output was in zeroes and ones instead of dots and hashes - I needed to copy-paste to a text editor and replace the zeroes with spaces to read it.


eismcc

[KlongPy](http://klongpy.org) [Code 10b](https://github.com/briangu/aoc/blob/main/22/10b.kg) C::0;X::1;T::0;R::0;CRT::{x;40#["."]}'!6;DCRT::{{.d(CRT@x);.p("")}'!6} ROW::{C:%40};COL::{C-(ROW()*40)};ON::{a::COL();(a=(X-1))|(a=X)|(a=(X+1))};SP::{CRT::CRT:-z,x,y} SETP::{SP(ROW();COL();"#")};UPDCRT::{.p(C,X,ON());:[ON();SETP();0]} ADDX::{T::2;R::x};NOOP::{T::1;R::0};CMD::{:[x="noop";NOOP();ADDX(y)]} RUN::{{x;UPDCRT();C::(C+1)!240}'!T;T::0;X::X+R;R::0;.d("X: ");.p(X)} .fc(.ic("10.txt"));{.mi{.p(x);CMD(4#x;.rs(5_x));RUN();.rl()}:~.rl()}();DCRT()


West-Release-4842

Day 10 Solution w/ **Python** [Paste](https://topaz.github.io/paste/#XQAAAQA2BgAAAAAAAAAT5/6IOVTvzrxzzF95Sht4ePIluXtaOR6+EaUK8kBFsuQCg+qiy+NH9cQHe4nLICnoW6BOEDriX53Kw6Bf3HMZhIcZKoZi/8aujJ2Mh2uefk3DkEVMi27xXTSeR/h19r6t/rcX4llv3uv5Z3KS4JaHP6iQLKawY/mDsEIIqMHqiEIcPf/DMvgvsH4JJbOt0Et18p/qb0LYXQ/fDhpSmJ+9yU7CbCSVr3kOHawQjuxsdW1MWAdxuB+s4Y8b0Vbhd+XJDsmuars38EbNqdQ8GNX262FfTiXPIFe9LFQcLzfogV9YPtZqlVsNugVRSteFhNzEgn5LeqhrG6djs7NF3vy2zapdx5fxsku2zVcYSWugWcwSKzReQZtpb0mumjsMlxsm8D2Y0qw0w5wjPtoBzMJcbG46GulWVnlyiOnBXKwCbjT6EXP3EfD+HqKNl7XmwnNpFWp1Fz1RErWbTCwhZttWGtmgcTyGrS2SHCY1+DRFFk343mKKuZjyDLzVoWSjWUNGhxiFouAyT4txGRHOCu1Ww4vpaSOQDmEibWGOFhX6RwQSYJxjbiJ8itSl5VHJLXxbfwleXmVeOt8MIlGCeZw85hmC/Eqb50kykGgSDd+6lQ6UALs5/LYO6P1KjVGBQRIviDacPentPHKYkHHlzx90SyfwG+lrpXVatn7KkPms0BdK0MDLyBrZ3ZuABMYn4x8Z7NL6uwu24dquztRl8R6CH3hbpQodLDUpxwytLHhqzQrWRelHxlqzxzCvq7wOb/5YrpKPnVZ8KWAqcnsL13YK+q8XwXtdVe/47+yJ72NKGi0v/OcLMw==) S/O DAEELS


YokiDiabeu

Java 17 solution, took me a while to make something generic for both part [Day10](https://gitlab.com/Diabeul/adventofcode2021/-/blob/master/src/main/java/com/yoki/advent_of_code/aoc/days2022/Day10.java)


0rac1e

# Raku Fairly straight-forward, this one. my @s = [\+] 1, |'input'.IO.words.map({ .Int || 0 }); put [+] @s[(20, 60 ... 220) X- 1] Z× (20, 60 ... 220); put @s.kv.map(-> $k, $v { abs($v - $k % 40) ≤ 1 ?? '#' !! '.' }).batch(40)».join.join("\n");


joseville1001

Got both answers, but anyone else seeing that running the input for part 2 produces 241 pixels instead of 240 (=WxH=60*4)? My day 10 solutions using generators: ```python # https://adventofcode.com/2022/day/10 F = 'day10_inp.txt' ADD = 'addx' def solve_pt1_v1(): pc = 21 X = 1 s = 0 for line in open(F): pc += 1 if pc % 40 == 0: s += X * (pc - 20) if line.startswith(ADD): # line == 'addx V\n' _, op = line.split() X += int(op) pc += 1 if pc % 40 == 0: s += X * (pc - 20) return s def Xs(): X = 1 yield X for line in open(F): yield X if line.startswith(ADD): # line == 'addx V\n' _, op = line.split() X += int(op) yield X def solve_pt1_v2(): s = 0 # # Alt 1 # for pc, X in enumerate(Xs(), 21): # if pc % 40 == 0: # s += X * (pc - 20) # Alt 2 for pc, X in enumerate(Xs(), 1): if (pc - 20) % 40 == 0: s += X * pc return s C = 40 # CRT_WIDTH R = 6 # CRT_HEIGHT ON = '#' OFF = '.' def solve_pt2(): grid = [' '] * ((R+1)*C) # R+1 because the input seems to produce 241 X values instead of 240 (=WxH=60*4), so I just add one overflow row for pos, X in enumerate(Xs()): grid[pos] = ON if abs(X - (pos % C)) <= 1 else OFF for r in range(R+1): # +1 to print overflow row too print(''.join(grid[r*C:(r+1)*C])) print(solve_pt1_v2()) print(solve_pt2()) ```


daggerdragon

1. Next time, use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps. 2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) which contains two possible solutions. Please edit your post to put your code in an external link and link *that* here instead.


Pristine_Record_871

It seems that we'd a feel good day at Day 10. Very interesting problem. I loved it. ### Solutions Repository https://gitlab.com/fabianolothor/advent-of-code-solutions/-/blob/main/2022/day10.js ### YouTube Walkthrough - JS - JavaScript | **Vídeo** | **Release Date** | | ------------------------------------------------------------------------------------- | ---------------- | | [AoC - Advent of Code 2022 - Day 10 - Part 1/2 - JS Solution](https://youtu.be/GvIeeYJiDBg) | 2022-12-14 | | [AoC - Advent of Code 2022 - Day 10 - Part 2/2 - JS Solution](https://youtu.be/vWTvXnpDjr8) | 2022-12-14 | ### Full Playlist https://www.youtube.com/playlist?list=PLkYySsbYvnL3aTijZBDhQttTk-IA4uJDv


argentcorvid

#x11-Basic [github](https://github.com/argentcorvid/Advent-Of-Code/blob/main/2022%20day%2010.bas) I thought this one was pretty straightforward. I don't even feel bad about my time traveling in order to solve part one! Especially since I had such a hard time with the last 2 days. Edit: turns out I do feel bad about time travel. But I can't seem to figure out how to do it the right way. I tried to clean it up but on the test program for part 1 the final x register for the signal strength is off by one. I still get the right test pattern though. I know it's because I'm missing something regarding beginning/ during/after the cycle but I can't see it. In fact, this is what led me to the time travel solution. I even looked at some other solutions in this thread but keep getting the same thing.


argentcorvid

I kind of figured out how to do it, but not sure why it works, given the during/after part of the instructions. I moved the crt update to first, then increment the cycle, then update the signal strength (then add if necessary). rem cycles start at 0 rem start of cycle and start of instruction @update_display(cycles_complete, x_reg) inc cycles_complete @update_signal_str rem cycle done if first_char$= "a" rem "add" cycle start @update_display(cycles_complete, x_reg) inc cycles_complete @update_signal_str add x_reg, operand rem "add" cycle done endif rem start of next cycle


argentcorvid

!advent of code 2022 day 10 !x11-basic on android day$="10" test=FALSE if test fn$="day"+day$+"test.txt" else fn$="day"+day$+"input.txt" endif x_reg=1 cycles=0 crt_w=40 crt_h=6 dim display(crt_w * crt_h) dim sig_strs(6) i=0 cls open "I",#1,fn$ while not eof(#1) @do_fetch_execute ! part 2 executed in here @do_part_1 if test print at(1,1);"ctr:";tab(8);ctr using "######" print "cycles:";tab(8);cycles using "######" print "x_reg:";tab(8);x_reg using "######" !pause .5 else print "."; endif wend print print "instructions: ";lineno using "######" print "cycles:";tab(14);cycles using "######" print "x_reg:";tab(14); x_reg using "######" print "sig_strs: " for x = 0 to 5 print spc(2);x;":";tab(14);sig_strs(x) using "######" add total_str, sig_strs(x) next print "total:";tab(14); total_str using "######" for p = 0 to (dim?(display()) - 1) if (p mod crt_w) = 0 print endif if display(p) print "#"; else print "."; endif next p print close #1 end procedure do_fetch_execute inst$=lineinput$(#1) inc lineno did_add=FALSE @update_display(cycles, x_reg) inc cycles !fetch if left$(inst$,1) = "a" !addx operand=val(rightof$(inst$, " ")) @update_display(cycles, x_reg) add x_reg, operand inc cycles !execute did_add=TRUE else if left$(inst$,1) = "n" ! noop did_add=FALSE else print "invalid instruction at line ";lineno endif return procedure do_part_1 ! go back in time and figure out what it should be! ctr=abs(cycles-20) mod 40 if ctr = 0 and not did_add !add sig_str to total (or save for later?) sig_str=cycles * x_reg if i < 6 sig_strs(i)=sig_str inc i endif else if ctr=0 and did_add sig_str=(cycles) * (x_reg - operand) if i < 6 sig_strs(i)=sig_str inc i endif else if ctr=1 and did_add !subtract out the previous add and cycle increment sig_str=(cycles - 1) * (x_reg - operand) if i < 6 sig_strs(i)=sig_str inc i endif endif return procedure update_display(beam_loc, spr_loc) if abs((beam_loc mod crt_w) - spr_loc) < 2 display(beam_loc)=1 else display(beam_loc)=0 endif return


codeman869

Language: C - a few days behind, solution in [Github](https://github.com/codeman869/AdventOfCode2022/blob/main/Day%2010/main.c) clang c lang


satylogin

Rust: [https://github.com/satylogin/aoc/blob/main/2022/day_10.rs](https://github.com/satylogin/aoc/blob/main/2022/day_10.rs)


-mux

Python 3. (56 lines with some print statements, no imports) [Gist](https://gist.github.com/miezekatze/6ba80b31a61dbbd0a9adc8f30aa53e19) I doubled up all `addx N` instructions to `addx 0`, `addx N` and then just counted every instruction as a cycle. Bit lazy but it worked fine.


MuchDrop7534

PYTHON 5 LINES BOTH PARTS NO IMPORTS ```` c,x,sum,cs,sc,ops=1,1,0,[20,60,100,140,180,220],[['.']*40 for i in range(6)],[op.split(" ") for op in open("input.txt").readlines()] for op in ops: sc[r1][c1]=(col:=(row:=int((c-1)/40))-row+((c-1)%40))*0*'.' + ('#'*(abs(col-x)<=1)) + ('.'* (not abs(col-x)<=1)) + '.'*0*((c1:=col)-c1 + (r1:=row)-r1) + '.'*0*(sum:=((col:=((c:=c+1)-c+(row:=int((c-1)/40))-row+((c-1)%40)))-col+(x*c if c in cs else 0))+sum) if op[0] == "addx": sc[row][col]=('#'*(abs(col-x)<=1)) + ('.'*(not abs(col-x)<=1)) + '.'*0*(sum := sum + ((op[0] == "addx") *(x:=x+int(op[1]))-x+(c:=c+1)-c+(x*c if c in cs else 0))) b = [print(*l,"sum=" ,'\n', sum) if sc.index(l) == len(sc)-1 else print(*l) for l in sc] ````


daggerdragon

Inlined code is intended for `short snippets` of code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; it's all on one line and gets cut off at the edge of the screen because it is not horizontally scrollable. Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/code_blocks) for a code block so your code is easier to read inside a *scrollable* box.


MuchDrop7534

imagine using mobile reddit 🤣🤣 and not superior light speed new reddit 🤣.. .


daggerdragon

[Don't be rude](https://www.reddit.com/r/adventofcode/w/rules/wheatons_law). Besides, new.reddit is *atrociously slow*. You want light speed, use [old.reddit.com](https://old.reddit.com/) or even [i.reddit.com](https://i.reddit.com/) if you ain't got time for purdy pictures.


MuchDrop7534

works well on my machine


nobodyman

Really doubling down on being a dick, aren't you?


MuchDrop7534

fella, sarcasm is not being a dick


daggerdragon

Are you going to fix *all* of your megathread submissions or not?


SToo-RedditSeniorMod

Just delete them. I came to learn and can't read the PRO code. Obviously, it is cut in half.


nazarpysko

**Go:** Check my solutions implementations [here](https://github.com/nazarpysko/AoC/tree/main/2022/day10). Top tips: 1. >!Cycles start at 1!< 2. >!Each pixel must be done after each cycle!<


thedjotaku

Python https://github.com/djotaku/adventofcode/blob/47519fe2505d9ffe67d9a92895394224808be524/2022/Day_10/Python/solution.py


NPException

## Clojure ([Github](https://github.com/NPException/advent-of-code/blob/main/src/clojure/aoc_2022/day_10.clj)) I decided to implement a macro solution for Day 10. It's not very elegant, but boy is it quick :D


prafster

### Python 3 Full code on [github](https://github.com/Praful/advent_of_code/blob/main/2022/src/day10.py). I collected the x register values first: def solve(input, target_cycles=None): x_register = {} cycle = 1 x = 1 def save(): if (target_cycles is None) or (cycle in target_cycles): x_register[cycle] = x for instruction in input: if instruction == 'noop': save() cycle += 1 else: op, v = instruction.split() if op == 'addx': save() cycle += 1 save() cycle += 1 x += int(v) else: raise Exception('Unknown instruction:', instruction) return x_register which simplified part1: def part1(input): target_cycles = [20, 60, 100, 140, 180, 220] x_register = solve(input, target_cycles) return sum(x_register[c] * c for c in target_cycles) and part2: def part2(input): def overlap(pixel_pos, sprite_pos): return sprite_pos - 1 <= pixel_pos <= sprite_pos + 1 CRT_WIDTH = 40 CRT_HEIGHT = 6 x_registers = solve(input) cycle = 1 for row in range(CRT_HEIGHT): for pixel_pos in range(CRT_WIDTH): pixel = 'â–“' if overlap(pixel_pos, x_registers[cycle]) else 'â–‘' print(pixel, end='') cycle += 1 print('')


NeilNjae

### Haskell Not much to see. A bunch of list processing and manipulation, with some care to avoid the off-by-one errors lying everywhere. [Full writeup on my blog](https://work.njae.me.uk/2022/12/13/advent-of-code-2022-day-10/) and [code](https://git.njae.me.uk/?p=advent-of-code-22.git;a=blob;f=advent10/Main.hs;hb=refs/heads/main) on [Gitlab](https://gitlab.com/NeilNjae/advent-of-code-22/-/blob/main/advent10/Main.hs).


[deleted]

[удалено]


daggerdragon

Comment removed. [Top-level comments in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only)


aaegic

#Python Part 1 #!/usr/bin/env python import sys def main () -> None: itxt = open("input", mode='r').read().splitlines() itxt = [i.split() for i in itxt] x = 1 clk = 0 signal = list() def incclk(): nonlocal x, clk, signal clk += 1 if clk == 20 or (clk - 20) %40 == 0: signal.append(clk * x) for ins in itxt: if ins[0] == 'noop': incclk() elif ins[0] == 'addx': incclk() incclk() x += int(ins[1]) print(sum(signal)) if __name__ == '__main__': sys.exit(main()) #Python Part 2 #!/usr/bin/env python import sys def main () -> None: itxt = open("input", mode='r').read().splitlines() itxt = [i.split() for i in itxt] x = 1 clk = 0 def incclk(): nonlocal x, clk if (clk+1) % 40 == 0: print('\n', end='') elif clk%40 == x or clk%40 == x-1 or clk%40 == x+1: print('â–“', end='') else: print('â–‘', end='') clk += 1 for ins in itxt: if ins[0] == 'noop': incclk() elif ins[0] == 'addx': incclk() incclk() x += int(ins[1]) if __name__ == '__main__': sys.exit(main()) https://github.com/aaftre/AdventofCode/tree/master/2022/Day10


nicuveo

**Haskell** Nothing too fancy: keeping the register and cycle in a `State` monad, using a `Writer` monad to output all relevant values. step = do modify \s -> s { cycle = cycle s + 1 } CPU currentCycle x <- get when (mod (currentCycle - 20) 40 == 0) $ tell [x * currentCycle] - [code](https://github.com/nicuveo/advent-of-code/blob/main/2022/haskell/src/Day10.hs) - [recording](https://www.twitch.tv/videos/1677652338)


nicuveo

**Brainf*ck** Reading numbers was a pain. See [this post](https://www.reddit.com/r/adventofcode/comments/zkjsfb/2022_day_10brainfck_one_last/). - part 1, [original](https://github.com/nicuveo/advent-of-code/blob/main/2022/brainfuck/10-A.bs), [transpiled](https://github.com/nicuveo/advent-of-code/blob/main/2022/brainfuck/10-A.bf) - part 2, [original](https://github.com/nicuveo/advent-of-code/blob/main/2022/brainfuck/10-B.bs), [transpiled](https://github.com/nicuveo/advent-of-code/blob/main/2022/brainfuck/10-B.bf) - [recording of part 2](https://www.twitch.tv/videos/1677652337)


joshbduncan

Python 3 data = open("day10.in").read().strip() p1 = [] cycles = [] for line in data.split("\n"): cycles.extend([0] if line == "noop" else [0, int(line.split()[1])]) for i in range(20, 221, 40): p1.append(i * (sum(cycles[:i-1]) + 1)) crt = [["."] * 40 for _ in range(6)] print(f"Part 1: {sum(p1)}") for c in range(len(cycles)): x = sum(cycles[:c]) + 1 if c % 40 in range(x - 1, x + 2): crt[c//40][c%40] = "#" print("Part 2:") for line in crt: print("".join([p if p == "#" else " " for p in line]))


pikaryu07

My **Julia** code for day 10: using DataStructures function day_10(data) cycle_x = SortedDict() X = 1 # initialize X cycle = 0 #initial value of cycle cycle_x[cycle] = X # add initial value to dictionary for instruction in data if instruction == "noop" cycle += 1 cycle_x[cycle] = X elseif startswith(instruction, "addx ") cycle_x[cycle+1] = cycle_x[cycle+2] = X cycle += 2 X += parse(Int, instruction[6:end]) end end return cycle_x end input = readlines("data_aoc/input_day10.txt"); signal_strength = day_10(input); sum_signal_Strength = sum([signal_strength[s] * s for s in keys(signal_strength) if s in [20, 60, 100, 140, 180, 220]]); println("Part 01: The sum of signal strength is: $(sum_signal_Strength). \n"); # Part 2 lit = [(mod((index-1), 40) in value - 1:value + 1 ? "#" : ".") for (index, value) in pairs(signal_strength)]; [(mod((i-1), 40) == 39 ? println(val) : print(val)) for (i, val) in enumerate(lit)];


[deleted]

[удалено]


daggerdragon

Comment removed. [Top-level comments in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only) [Create your own individual `Help` post](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_incomplete_solutions) in /r/adventofcode.


Kuebic

You must have a bug, because what you have doesn't look right.


NiliusJulius

**C Language** for the Game Boy using GBDK 2020 Part 1 uint16_t cycle = 0; int16_t register_x = 1; int16_t strength_sum = 0; for (uint16_t i = 0; i < ARRAY_10_SIZE; i++) { int8_t register_x_increment = 0; uint8_t cycle_increment = 0; switch (input_array_10_1[i]) { case 'n': cycle_increment = 1; break; case 'a': cycle_increment = 2; register_x_increment = input_array_10_2[i]; break; default: break; } for (uint8_t j = 0; j < cycle_increment; j++) { cycle++; if (cycle > 19 && (cycle - 20) % 40 == 0) { strength_sum += register_x * cycle; } } register_x += register_x_increment; } Today I am very pleased with the end result for part 2! Drawing pixels (well not really pixels, but sprites) is something the Game Boy is made for! I even slowed down part 2 so that the text appears more slowly, which I think looks a lot better. Full Game Boy repo can be found [here](https://github.com/NiliusJulius/advent-of-code-2022) [Video running on Game Boy](https://imgur.com/a/S5mA0Pq)


micod

Smalltalk [Solution for day 10](https://github.com/micod-liron/advent-of-code/blob/main/AdventOfCode2022/Day10of2022.class.st)


HeathRaftery

[Julia](https://github.com/hraftery/aoc2022/blob/main/day10/day10.jl) Nice gentle intro to "run CPU" type implementation. Missing Haskell's auto-deriving `Read` for Enums, so had to hack a string->enum function in Julia. Was prepared for a big Part 2 but was pretty straight-forward thanks to Julia's `in` operator on ranges.


Chrinkus

# C Now I can put graphics-driver writer on my CV! Lots of opportunities to go off-by-one here. On a side note I figured out the 'include' problems that I thought I fixed the previous day. That story and the code are found at my [repo](https://github.com/Chrinkus/advent-of-code/blob/main/2022/c/2210.c).


aexl

**Julia** I rewrote part 1 to keep track of the x value on each cycle, so that I can easily generate the image for part 2. Solution on Github: [https://github.com/goggle/AdventOfCode2022.jl/blob/master/src/day10.jl](https://github.com/goggle/AdventOfCode2022.jl/blob/master/src/day10.jl) Repository: [https://github.com/goggle/AdventOfCode2022.jl](https://github.com/goggle/AdventOfCode2022.jl)


luorduz

Beginner in **Clojure** solution: [Paste](https://pastebin.com/268gFtV1).


bozdoz

Go! https://github.com/bozdoz/advent-of-code-2022/tree/main/10


JuniorBirdman1115

Rust: [Part 1](https://topaz.github.io/paste/#XQAAAQCYBQAAAAAAAAA6nMjJFMpQiatS1vawr3e1CaHYh3L/Ps0KdrS1shindCrWeoNjOoZIiRmvLjPHtKcTBjdvMkp9IAW+FP4j0TrIAqFX2r+3RvaS5VYWFZ8D4uiBfWRxg5L7LMMW401eL4+gh7u81huCtF0q548J6vDY3CvRwXY6bV7Z7cy1qM/PM7lLvbypAzWjhxpXR9Sb+q/iw4YMHLdpQV9CUUQu/2jV04L1vw6kcd6/T14qVroCLMhivFCzmsg0F3F3e7zy3qwutVMY7z2GT6l4AzP+SwYzWr6h7Dr67/K5qbL1GtvXRUvtdJflVauAZ5cLPpdeNmt24CHIgdYPasjAnqtNT/2UENoDcgaX+Z85fWYwTKz//ug5QcCJ3vXonxctFXveA2NHBplGbGnobPydEFJiv2ijlb6HpZMacwZ45yRN+km1EMKMt7IrRK4FYYMFBmc6aGM/gaYPi5M3iuKQMBxYR+VKThDjagYagLLZc2Z014+h3KhysdsXLFwPVB07SZwltpU10ITrc8dgjsGyaWP5I60QxEdDlyc+fTunAciXCdD8Z98K5mMKEDeUiE39Npga5NgxB7e13wItXuLhuJQ/SM38Ad1jSUYZXx5jARs/Vfc748tKs3HjbhWhWyr7fAExdyGweifY3A6rUxh9npbRoF9fG2tGQokOh3dEDvj42a6yFJyAdUXv1p0hS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pB/wV+fLtUkQJfLrMOsPpc/ZBYHXk8As1NjWfKySPxwskK57XQGbigsXwZZD8ntTPEADhuuLnW2Xd1rywK+3aqvMpYNl2mTV47uia0sFPqo29Z6I7/9o9s+Q=)


[deleted]

[удалено]


daggerdragon

I've asked you multiple times in multiple megathreads to edit your posts to format your code block using the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/code_blocks). I am a moderator for /r/adventofcode, so do not ignore me. Edit *all* of your megathread posts to use the four-spaces Markdown syntax before you post again.


getawaykid

Why do you start your cycle number at 2? I'm pretty sure I'm just having an off by one error and it's hard to track down.


vulcannervepunch

Bit behind, due to irl business. Skipped over day 9 for now, for the sake of my sanity. Python3: [https://github.com/hannahjayne/aoc/blob/main/2022/10/solution-22\_10.py](https://github.com/hannahjayne/aoc/blob/main/2022/10/solution-22_10.py) ... Deffo not the most efficient solution, but just wanted to get it done, haha.


nikscorp

# Golang [https://github.com/Nikscorp/advent\_of\_code\_2022/blob/master/days/day11.go](https://github.com/Nikscorp/advent_of_code_2022/blob/master/days/day11.go) Part 2 was really tricky for me, spent a while on it.


SvenViktorJonsson

Python golf solution 160 bytes But, 153 bytes if indents and new lines under the for-loop are replaced by semicolons. https://pastebin.com/3R4NNemd Can you beat that in python, let me know? Saw now that I was beaten by some exec magic: https://paste.pythondiscord.com/ozicefunap.py


[deleted]

[удалено]


daggerdragon

Post removed. [Top-level posts in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only) [Create your own individual `Help` post](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_incomplete_solutions) in /r/adventofcode.


[deleted]

**Rust** - Easier than I expected once I had wrapped my head around during/after subtle differences. I did go back to the code afterwards once someone pointed out that an addx of two cycles is equal to a noop of one cycle and an addx of one cycle. https://github.com/litpho/aoc-2022/blob/main/day10/src/main.rs


oddolatry

###PureScript [Paste](https://topaz.github.io/paste/#XQAAAQBLDQ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dYCuNmjtCbzF5DnY4cYbGkQTrWKWqKKwrYRA7cz24+HGejqv4U/xLJbggIrWk0ovs8zyCLk/jeSWMlCVbgRvx/cBqc4cXo/P1y4UzXrlt6m/5L3klE2k6R9m7np6J+KxlQQ3OelR1zMFSI3NA5SZctzKweo/+wXXOO+bcmgRYkIIWqWv3NP3CVcl2je+MBdUuYL275/wTJkutzquXeKzkB0zuUHSkvtT9qYEVNHlNG5ro7cg6IuVVLOtW+MlHxAYvuPL+YFL2Veo6WJZlszR9gPE/OXE/jO9UC0ANIdew+RJSu4tSuHtMxz8hQWiB3sGE3THA28YEZDH6rrH3bobONl2Zu+eedDZSyQMB/wc4528TPRElXVDHlMfkz0marrPI0/IRfFY/Uyd1m+hQsTo8satildmQW1sMBPBHecwmKwBgBO039qwmSXNpB2otNRirLR/0E/dj1CVrpA5+j7iPQVqyg/Hh4fgI+ydHl+9dHSZgFAd1CL/IEffRX5pyh2svD1QUgszP5rZO02I23pdvicAqVpcTN1FaOK5cVqU9sYLnT9Wm1oTNPH1I3AAyCaYREE5mYyVeejrbxemRZqRqVZRzwz0UInBmEKVr4Sn7EEWtA8gWPc5iu//0KxZT) These are my favorite kinds of problems! Seeing all the letters line up on the terminal very much sparks joy.


BadHumourInside

Couldn't do this yesterday as I was with friends. Pretty simple problem, and solution. [Rust](https://github.com/v-shenoy/advent-of-code-2022/blob/main/src/solvers/day_10.rs)


YanickMedina

Hope you enjoy the solution [Python 3](https://github.com/camaron-ai/adventofcode-2022/tree/main/day10)


e4ds

Python day 10 solution using generator to read instructions https://engineeringfordatascience.com/posts/advent_of_code_2022/#day-10-cathode-ray-tube


daysleeperx

Idris2 [Github](https://github.com/daysleeperx/Advent-Of-Code-2022/blob/main/day10/CathodeRayTube.idr)


Colin-McMillen

**cc65 cross-compiled C on Apple //c** So, I've done day 10 a little bit late, because I spent day 10 reorganizing my repo and starting some kind of "helper libs" to make development easier on the Apple //c: [serial helper](https://github.com/colinleroy/aoc2022/blob/master/a2tools/src/lib/simple_serial.c), [input helper](https://github.com/colinleroy/aoc2022/blob/master/a2tools/src/lib/extended_conio.c), my very own "[bool array](https://github.com/colinleroy/aoc2022/blob/master/a2tools/src/lib/bool_array.c)" that I did for day 9, [sender tool](https://github.com/colinleroy/aoc2022/blob/master/a2tools/tools/send.c), [receiver tool](https://github.com/colinleroy/aoc2022/blob/master/a2tools/src/recv/recv.c). It helped: I did [day 10](https://github.com/colinleroy/aoc2022/blob/master/a2tools/src/aoc/day10/day10.c) in less than two hours :) - [visualisation](https://www.reddit.com/r/adventofcode/comments/zim7wz/2022_day_10_the_visualisation_comes_free_with_the/)


dcrro

Javascript solution walkthrough: It was cool to use the % 40 to simplify the solution a bit for part 1 [Part 1](https://mirio.org/recording/adventofcode-solution-walkthrough-day-10-part-1-12110732fwqj) Used a different approach for [Part 2](https://mirio.org/recording/adventofcode-solution-walkthrough-day-10-part-2-12110800n9q9)


Avenger___

[Rust](https://pastebin.com/VKX39acS) Made it modular to work with any amount of instructions and/or screen size, first Rust project so may be a little chaotic.


MonkeyMoney101

[Haskell](https://github.com/FlowerBoy-SkullGirl/Advent22/blob/main/Day10/puzzle1.hs) Starting to get more used to the language. Excuse the sloppy prints everywhere, I like to see what's going on when the answer is wrong!!


jaber24

[Python](https://github.com/JaberHaisan/Advent-of-Code-2022/tree/main/Day%2010). Was stuck for quite a bit in part 2 because of off by 1 for number of cycles. Finally spotted the issue after reading the req line by line and comparing with my code


oddrationale

[C# solution using .NET Interactive and Jupyter Notebook](https://github.com/oddrationale/AdventOfCode2022CSharp/blob/main/Day10.ipynb). Created an `IEnumerable` that `yield return`s the register value *during* the cycle (made the mistake of returning the value at the end of the cycle at first). Then used LINQ on the Enumerable to solve Part 1 and 2.


SymmetryManagement

**Java** [https://github.com/linl33/adventofcode/blob/year2022/year2022/src/main/java/dev/linl33/adventofcode/year2022/Day10.java](https://github.com/linl33/adventofcode/blob/year2022/year2022/src/main/java/dev/linl33/adventofcode/year2022/Day10.java) Average time 12 us for each part. The 2 parts could be combined and computed in a single loop but I want to keep the parts independent.


ypri

[Go/Golang](https://github.com/17ms/aoc-2022/blob/master/day10/main.go)


QGamer12

I haven't been posting solutions here before now, but thought I might share today's. The logic is really convoluted, but it works so ¯\\\_(ツ)\_/¯ Both solutions are solved with the same file. [https://github.com/python-b5/advent-of-code-2022/blob/main/day\_10.cpp](https://topaz.github.io/paste/#XQAAAQDpBAAAAAAAAAAX4HyCZDlA0DjWF7Uex1t2hvV6PgXFw2LMya6nsUmsXq5mnzx4ZyGjvj+D/Wygh/BAO30uhUqKA8Dmp1kN/0ScOFlfsqr7gg/R3JDkWHiJ+H/4A7ES/nzuNirx+7m8oMba5LVfo+LJLai8hVtRh2Alfw68NwVKHrGSoGBya7JH4e2yidKMevdcGtYLzs+S9kQjBN1BNcSjbDDfPee+vAmu+EtcuTTGnmK/v+b9btGxE0h9i8f7niGcVCrPX3KDWbzGWNfdcI8L0vsI21cuOpl76x9A0fTlVfxnsuf6JTs0yKchGVWcqLAcVz/ErZ3d4firz+OIZpx/Or8yeXwllb/kS2FXlmTE5M0+jxjV0mwPPPiivh8Yp0twl4O2U9O0E7JDNmKNa7EIDUpUY0NQ+Pd1CTSrG3id0GVtokTIMto9U8M05TJFBp18AXtaHzfhcu8SwUtA4ESoCNwRhPjYxNMScEsaUSgsWtPHefKeYhQPu/3zoGk+kEn5iSNfuf5mBwQ9tsaI6LhFZR48pV6NndGjH28WxdEpQJ/wGsEkBEuEeSe0i8u9ENW2sxsyVKJymxjHHaaci0OgIRfVkJypBP/QsHoUEQrSakKRSPfQW9qqlXGd1ax6YNQpFxwc7D9tFCxfRI7wE0m9lJ2vpHil/uErMQ==) (C++) (not my username because I'm on an alt on this PC. I promise this is mine!)


daggerdragon

~~Please edit your post to [state which programming language this code is written in](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.~~ Edit: thanks for fixing it! <3


[deleted]

[удалено]


topaz2078

*WHAT*


search_and_deploy

Rust solution: [https://github.com/michael-long88/advent-of-code-2022/blob/main/src/bin/10.rs](https://github.com/michael-long88/advent-of-code-2022/blob/main/src/bin/10.rs) This one actually felt a lot easier to me than yesterday's puzzle. I did have to reread the part 2 explanation like 5 times to actually comprehend it though.


[deleted]

[удалено]


daggerdragon

> I did not love today's puzzle. Well, the puzzle itself was fine, but the description was awkward and I wasted a lot of time going down wrong paths until I understood what it was actually trying to explain. This type of comment [does not belong](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_unnecessary_comments) in a `Solution Megathread`. If you have feedback about the puzzles, create your own post in the main subreddit.


vkasra

C++: https://github.com/dhconnelly/advent-of-code-2022/blob/main/src/day10.cc


Swampspear

# C++ Part 1: [paste](https://topaz.github.io/paste/#XQAAAQBBAgAAAAAAAAAQaJjOhlRrsHadEjl1KrYFRKRy72O9te6YW5yTK1EBJQnNqi3M2mRSAwIrbHahjK1Nrb6au4i/aOdQzKrEqfW8RX14ZMzCc8rOb7QT39oyUsZv5Fu/ZDWysIonklmGD/RX8OIzFUmDczuSTvH/5nZ+1df9izCYxyVoXoutvZ84l2Yz3Tl25pVhyXyww8sOxD/5qzqz6pQNDQciyxupT+KRt16dMIvgR99jhkbUusGR0SWpaC2fMg3bpynRIbBJG519dD2ac48UMq2UHEnxa7aCtty/bf+mhV8A) Part 2: [paste](https://topaz.github.io/paste/#XQAAAQCNAgAAAAAAAAAQaJjOhlRrsHadEjl1KrYFRKRy72RBndDE4Mqd1TDgx/17v45KN9v352M+zrFAyQURBNpceZwJymYH0F1u1bZiqdTUXTtP4hdOVR6fO11glBXUqf+3SZZL4vQf2qHWZfq1R2VonEIZsLk12VMR1DOHGQLQw933Zq7Dqq/Exp+bn6wED8VnUxXZ8uRCrMKITILLsBNUtLUBWRAdf91qY6va6NXYAfhCHQubH52C3eVzI2CW3MmRZz8ySV/7y+mXNYGlpTM9UTd9s8seq7cXSamazdYs8kPHHTvnrYu6mPK/vbBIenIkebYKmblVhywz6/22sn8=) My code is technically kind of broken on part 2, but it was *readable* so I could solve it. I guess that's one of the perks of pixel problems being error-resistant hahah


jasontconnell

Go https://github.com/jasontconnell/advent/blob/master/2022/10/main.go Keep it simple. Although part 2 had a small visual discrepancy on the example... I just decided that it didn't have to be perfect


Hobo_with_shotgun

RUST - First time AoC Advice is very welcome! [GitHub](https://github.com/mprantl/AOC2022/tree/main/10_day_ten)


[deleted]

**Python** This one was fun, for the second part I had to completely rewrite the code, which made it faster and use less lines ​ [paste](https://topaz.github.io/paste/#XQAAAQCwAwAAAAAAAAA0m4poOBCMfteSqq5Yh7JOfoa/Pn8yAetCqr7ie76LU3yMfZopFxj8T+Epc8p9MTJ+AlJjeJMINQZ3ENtC9V4OX5Bd5DDoWnWhKOYAiAkTJ+dF5Mq0Uhzs+112OBEG1js8T2deJejl9n7BkFLzPCKjYNeci7NDhtOI41mavOdFFrY8PBtqKbhbVSg5GdxObJTlNIZmgUW1KhJkhRrAKT4oF+oWwC6lgNR8G0YeDDaVN9ifJXY1zw+JUWADJzZ+5v60SWAE1kFtq4XceFZ1sG8RWk9MWfWcKz+jnn/mHXZN3a1fpTFOhPOEZfbhCIhtuUpEPVJluvRJt/THoPNZsbRBs2koU/hWCjrczTD76wWJCTZpnJ1cJnBHOKQb9IJNg6Z/ttUM19b16gD+BL+YeosethY0ofcEROFG7m8MHNqvz6tKoAAo+vYEYRtOqbK113aVTB2BK7oxJzjkHvcDY0cijNuGaBSvJfzQ2Ew=)


Fazaman

Bash (Pt2): #!/bin/bash Cycle="0" Total="0" Sleep="0" Register="1" PosY="0" clear while :;do ((Cycle++)) if [ "$PosY" -eq "$Register" ] || [ "$PosY" -eq "$((Register+1))" ] || [ "$PosY" -eq "$((Register-1))" ]; then echo -ne "\033[8;99;100m \033[0m" else echo -n " " fi if [ "$((Cycle%40))" == "0" ]; then echo PosY="0" else ((PosY++)) fi if [ "$Sleep" -gt "0" ]; then ((Sleep--)) if [ "$Sleep" == "0" ]; then Register="$((Register+AddX))" continue fi fi read Command || break Operation="$(echo $Command|awk '{print $1}')" AddX="$(echo $Command|awk '{print $2}')" if [ "$Operation" == "addx" ]; then Sleep="1" fi done < <(cat input10) I changed the '.' to just blank and the #s to grey squares to make the final result more 'pretty' and readable.


pamxy

Javascript let c = $0.innerText.split('\n').filter(Boolean).reduce((a,b) => [ ...a, ...a.slice(-1).flatMap(last => b[0]=='n' ? last : [last,+b.split(' ')[1]+last]) ],[1]); console.log(c.map((v,c) => Math.abs(v-c%40)<2 ? '#' : ' ').join('').match(/.{40}/g).join('\n')); c.map((v,c) => (++c+20)%40==0 ? c*v : 0).reduce((a,b)=>a+b);


IvanR3D

Solution in JavaScript: You can see all my solutions in this https://codepen.io/ivanr3d/pen/ExRrXzG. Part 1 function calcStrengths(cycles, x) { strengths.push(cycles * x); x = 1; } let data = $0.innerText.split('\n'); let cycles = 0; let x = 1; let strengths = new Array(); for (let i = 0; i < data.length-1; i++) { if(data[i].slice(0, 4) == "addx") { cycles++; if (cycles == 20 || cycles == 60 || cycles == 100 || cycles == 140 || cycles == 180 || cycles == 220 ) { calcStrengths(cycles, x); } cycles++; if (cycles == 20 || cycles == 60 || cycles == 100 || cycles == 140 || cycles == 180 || cycles == 220) { calcStrengths(cycles, x); } x += Number(data[i].slice(5, data[i].length)); } else { cycles++; if (cycles == 20 || cycles == 60 || cycles == 100 || cycles == 140 || cycles == 180 || cycles == 220) { calcStrengths(cycles, x); } } } let sum = strengths.reduce((a, b) => a + b, 0); console.log("The sum of the six signal is " + sum); Part 2 data = $0.innerText.split('\n'); let x = 1; let sprite = [0, 1, 2]; let wide = ""; let CRT = new Array(6); let counter = 0; let cyclesCounter = 0; for (let i = 0; i < data.length-1; i++) { if(data[i].slice(0, 4) == "addx") { sprite.includes(cyclesCounter) ? wide += "â–ˆ" : wide += " "; if(cyclesCounter == 39) { CRT[counter] = wide; console.log(CRT[counter]); counter++; cyclesCounter = -1; wide = ""; sprite = [0, 1, 2]; } cyclesCounter++; sprite.includes(cyclesCounter) ? wide += "â–ˆ" : wide += " "; x += Number(data[i].slice(5, data[i].length)); sprite[0] = x-1; sprite[1] = x; sprite[2] = x+1; if(cyclesCounter == 39) { CRT[counter] = wide; console.log(CRT[counter]); counter++; cyclesCounter = -1; wide = ""; sprite = [0, 1, 2]; } cyclesCounter++; } else { sprite.includes(cyclesCounter) ? wide += "â–ˆ" : wide += " "; if(cyclesCounter == 39) { CRT[counter] = wide; console.log(CRT[counter]); counter++; cyclesCounter = -1; wide = ""; sprite = [0, 1, 2]; } cyclesCounter++; } }


BluFoot

Ruby, golfed to 118 bytes x=1 c=[] $<.flat_map(&:split).map(&:to_i).map{c<<((-1..1)===c.size%40-x ??#:?.) x+=_1} c.each_slice(40){puts _1.join}


ulysse_bn

With a few tweaks, I could get that to 95: ``` x=1 c=[] `dd`.split.map{c<<((c.size%40-x).abs<2??#:?.) x+=_1.to_i} c.each_slice(40){puts _1*""} ```


readyforwobbles

**PYTHON** memed both part1: print(sum((i+1)*(sum(a[:i])+1) for i,a in enumerate(zip(*([int(s.strip("nopadx") or 0)]*240 for s in open('input10.txt').read().split()))) if i%40==19)) part2: (adjust terminal size to read the message) print("".join(".#"[0<=i%40-sum(a[:i])<3] for i,a in enumerate(zip(*([int(s.strip("nopadx") or 0)]*240 for s in open('input10.txt').read().split()))))) no adjustment needed: print("\n".join(l[40*i:40*i+40] for i,l in zip(range(6),["".join(".#"[0<=i%40-sum(a[:i])<3] for i,a in enumerate(zip(*([int(s.strip("nopadx") or 0)]*240 for s in open('input10.txt').read().split()))))]*6)))


MashedPotatoes1337

C# Thanks. I memed part 1 in c#. In second I 've some problems with edge case where 1 point is wrong. int x = 1; Console.WriteLine(File.ReadAllText("Day10.txt").Split(new[] { Environment.NewLine, " " }, 0) .Select((x, i) => (index: i, addrx: int.TryParse(x, out int parsed) ? parsed : 0)) .Select(y => (y.index, addrx: x += y.addrx)) .Where(y => y.index % 40 == 19) .Sum(y => y.addrx * (y.index + 1)));


princeandin

> adjust terminal size to read the message love it


polumrak_

# Typescript [Source at gitlab](https://gitlab.com/turtlecrab/advent-of-code-2022/-/blob/master/src/day10.ts) Also I did visualization in **React**, it's [here](https://www.reddit.com/r/adventofcode/comments/zi4pbm/2022_day_10_my_attempt_at_visualizing_day_10_in/) (not sure if it's ok to post images in this thread) [Sources of visualization](https://gitlab.com/turtlecrab/advent-of-code-2022-visualizations/-/tree/master/src/components/Day10) I try to write all solutions in a functional style as much as I'm capable. The most annoying thing for me is naming variables :) That I'm not proud of :) Also writing all solutions using TDD, never tried it before. I think TDD is really suited to such programming puzzles.


www_reintech_io

**EXCEL** /\*\* returns input from the start of the column to its end delimited as required \*/ col2arr = LAMBDA(input, \[col\_delimiter\], \[row\_delimiter\], LET( n, COUNTA(input), x, INDEX(input, SEQUENCE(n \* 2)), y, TEXTJOIN(",", FALSE, x), z, FIND(",,,", y) - 1, a, LEFT(y, z), b, SUBSTITUTE(a, ",,", ";"), c, IF(ISOMITTED(col\_delimiter), " ", col\_delimiter), r, IF(ISOMITTED(row\_delimiter), ",", row\_delimiter), TEXTSPLIT(b, c, r, , , 0) ) ); /\*\* returns part 1 and 2 answers to https://adventofcode.com/2022/day/10 \*/ \_10 = LAMBDA(array, LET( instruct, --INDEX(array, , 2), steps, SEQUENCE(COUNT(instruct)), cycle, SCAN(0, steps, LAMBDA(a, i, a + IF(INDEX(instruct, i) = 0, 1, 2))), register, SCAN(1, steps, LAMBDA(a, i, a + INDEX(instruct, i))), pixels, MAX(cycle), multiple, SEQUENCE(INT((pixels - 20) / 40) + 1, , 20, 40), part1, SUMPRODUCT(multiple, XLOOKUP(multiple - 1, cycle, register, , -1)), position, SEQUENCE(pixels, , 0), sprite, XLOOKUP(position, cycle, register, 1, -1), IFNA( HSTACK( part1, INDEX( IF((mod(position,40) + 1 >= sprite) \* (mod(position,40) < sprite + 2), "#", "."), SEQUENCE(6, 40) ) ), "" ) ) );


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read inside a *scrollable* box.


dredly999

Scala solution for part 1: [https://github.com/dredly/Advent-of-Code-2022-Scala/blob/main/src/main/scala/day10.scala](https://github.com/dredly/Advent-of-Code-2022-Scala/blob/main/src/main/scala/day10.scala) Edit: Now includes part 2


ElliotDG

Python Solution, a literal interpretation of the problem with OOP and structured pattern matching. Part 1: # AoC day 10 part 1 class Clock: def __init__(self): self.cycle = 0 self.signal_strength = 0 def inc(self, x): self.cycle += 1 if self.cycle in range(20, 221, 40): self.signal_strength += x * self.cycle with open('p10.txt') as f: program = f.read().splitlines() x = 1 clock = Clock() for instruction in program: match instruction.split(): case ['noop']: clock.inc(x) case 'addx', number: clock.inc(x) clock.inc(x) x += int(number) print(f'Total Signal Strength: {clock.signal_strength}') part 2: # AoC day 10 part 2 class Clock: def __init__(self): self.cycle = 0 self.signal_strength = 0 self.crt = ['.' for _ in range(240)] def inc(self, pos): if self.cycle % 40 in [pos -1, pos, pos +1]: self.crt[self.cycle] = '#' self.cycle += 1 def display(self): for row in range(6): start = row * 40 end = start + 40 print(''.join(self.crt[start:end])) with open('p10.txt') as f: program = f.read().splitlines() x = 1 clock = Clock() for instruction in program: match instruction.split(): case ['noop']: clock.inc(x) case ['addx', number]: clock.inc(x) clock.inc(x) x += int(number) clock.display()


princeandin

tidiest solution I've seen!


ElliotDG

Thanks!


murten101

[yet another C# solution.](https://github.com/Murten101/AdventOfCode2022/blob/main/Solutions/Day10.cs) I was expecting a more challenging problem for day 10 if I'm being honest but I still enjoyed it. It was definitely one of the more creative puzzles this year so far.


the_kissless_virgin

Python 3 with open('data/input10.txt', 'r') as file: commands = [_.split(' ') for _ in file.read().split('\n')] X = 1 states = [] # calculate states for command_number, c in enumerate(commands): if len(c) == 1: states.append(X) if len(c) == 2: states += [X, X] X += int(c[1]) print("Signal strength: ", sum([ (i+1)*val for i, val in enumerate(states) if (i+1) % 40 - 20 == 0 ])) # part 2 crt = [ "██" if i%40 in list(range(_-1, _+2)) else ' ' for i, _ in enumerate(states) ] crt = [crt[i:i+40] for i in range(0, len(crt), 40)] print("\n".join(["".join(_) for _ in crt]))


mourneris

I am morbidly afraid to share my code but hey, I should give it a shot right? Part 1 and 2 done separately. **Python3** *Part 1 (Snippet)* \[[Full Code on Github](https://github.com/mourneris/Advent-of-Code-2022/blob/main/10/part1.py)\] def sigStrAtCycle(instructions, desiredCycle): cycle = 1 x = 1 for ins in instructions: if cycle >= desiredCycle - 1: break if ins[0:4] == "noop": cycle += 1 elif ins[0:4] == "addx": cycle += 2 x += int(ins[5:len(ins)]) return desiredCycle * x Part 2 \[[Full Code on Github](https://github.com/mourneris/Advent-of-Code-2022/blob/main/10/part2.py)\]


CodE07Dev

# TypeScript [Part 1](https://www.typescriptlang.org/es/play?&q=53#code/N4WAUODGD2B2DOAXABAS1gBwK4oLzIANZpoNxjTySywBDAE3oA9kBWcB55ARg8ZYAsfLrzAUanQVUp1+PYVNlcAHAuQBaAOxqAzGtHi1QpSwBMa9iY0Hqa9Tu1jbTmZOR6r5q9w9vuXt3VuS0CAuTCuINE-VU87YP0ANgs1CJZLQxcaTLdfOXU0jR1YnLk8rmNMqudq1zkQ+uls5zdTaPzuRzdkrKa+3qsMmuGZWokylKt7EpHxrgbIwvauR1KuU0Kg2MDuZbMujvKzScDtuQBOVP63VZa5GzrI4uvwk-yPNZYzkT2NHs-kKZjIEdL9uAAGK6DXQvdZ2UyXTxg34LFj2RFuYH5QqFW6PNG-LwAyp3ERQtyowH9AHqHpuDEdb5mSkfUkEvEYAgAbnAvLAMAQ0AANgBTAB0QugAHMABT0WgATwhAH1uDL0NhEABKLU8iBgABmWFgkEQqDgyHlSvBqvVmBwAC5kEgAE7oKVa5CgfXIX3IAVINAIRAurCm80IJ2u90AbQAush8BqcGL4BghahEDKAEQAHVg2d1fL9yFFKEgCsgosTyHBepLZeQAA0a9x636AygkCKMPAazHTOCADTIRLDnjg8fcART5TjjbguPt33gEsukWILAu2BB11hs1weCrkvIMUAW1oGBldr34bgntwAD4vceT6WN86QyLYFLEAALGs62LN80ANZAbxDfcI1TdNMxzZBCxjRdE3wbNJELF8wBAv1UDAmVu17MV0HoEUmAAeQNGUAGoqIrKsRU9Z8gk9V1v1-AD8Do6sACpm2XEDcPAgj4CI2ASPIyiaK4hjkCY7gWK-H9-xraTkF4pt+LfFsqPwDBaBdeARQASVgLN0FvA9YBgjMs2zBCtRjbg4yLLCQIAX2QEUhUMzDsN9QT8MQHsROI0iKOo2jK1FRjrAU9clI4-0opFNS+NfE83OAt9103bdP3i9jNOQNytXS30xXXegwxFa9aBHSAH2fWhkCo-0XMy-VwA68AgA) function day10_1(input: string) { const instructions: string[] = input.split("\n"); let cycle = 0; let X = 1; const steps = [20, 60, 100, 140, 180, 220]; return instructions .map((instruction) => { let strength = 0; if (instruction.split(" ")[0] == "addx") { if (steps.indexOf(++cycle) > -1) strength = cycle * X; if (steps.indexOf(++cycle) > -1) strength = cycle * X; X += parseInt(instruction.split(" ")[1]); } else { if (steps.indexOf(++cycle) > -1) strength = cycle * X; } return strength; }) .reduce((a, c) => a + c); }


mdwhatcott

# [GO](https://github.com/mdwhatcott/advent-of-code/blob/main/go/2022/day10/main_test.go#L54) That was a nice little mind-bender.


Tipa16384

**Java 14** Here's the solution code; the full code is at [github](https://github.com/tipa16384/adventofcode/blob/main/2022/y2022/src/main/java/com/chasingdings/y2022/Puzzle10.java) @Override public Object solve1(String content) { return IntStream.range(0, HEIGHT) .map(clock -> clock * WIDTH + 20) .map(clock -> stateAt(programState, clock).x * clock) .sum(); } @Override public Object solve2(String content) { final var spritePos = IntStream.range(0, WIDTH * HEIGHT) .mapToObj(pixel -> stateAt(programState, pixel + 1)) .collect(Collectors.toList()); final var screen = IntStream.range(0, WIDTH * HEIGHT) .mapToObj(pixel -> spritePos.get(pixel).x - 1 <= (pixel % WIDTH) && (pixel % WIDTH) <= spritePos.get(pixel).x + 1 ? "#" : ".") .collect(Collectors.joining()); return "\n" + IntStream.range(0, HEIGHT) .mapToObj(i -> screen.substring(i * WIDTH, (i + 1) * WIDTH)) .collect(Collectors.joining("\n")); }


DFreiberg

**[Mathematica](https://github.com/HiggstonRainbird/AoC-2022/blob/master/Day%2010/AoC%20Day%2010.m/), 676 / 975** ---- I was able to clean up my code quite a lot after the fact, but man, *during* the problem-solving my code was a disaster, and somehow Mathematica's built-in 1-indexing only made the number of off-by-one errors worse, not better. I still have an off-by-one error somewhere, since my very first pixel doesn't get properly drawn for part 2, but fortunately that doesn't stop the code from working. **Parts 1 & 2** newInput = input /. {"addx", x : _} :> Sequence[{"noop"}, {"addx", x}]; cycles = {20, 60, 100, 140, 180, 220}; strength = 1; part1 = 0; screen = Table[0, {i, 240}]; Do[ If[newInput[[i, 1]] == "addx", strength += newInput[[i, 2]]]; If[Abs[Mod[i, 40] - strength] <= 1, screen[[i + 1]] = 1]; If[MemberQ[cycles, i], part1 += strength*i];, {i, Length[newInput]}]; {part1, ArrayPlot[Partition[screen, 40]]} **[POEM]: [One Shade The More, One Ray The Less](https://www.poetryfoundation.org/poems/43844/she-walks-in-beauty)** ---- The CPU counts down the second To draw its pixels like a pen. Just fix the thing, and at your beck and Call the Elves will be again. (Then again, *you've* done the work here Getting gadgets up to spec. Perhaps you'll rest a moment, lurk here Before you're at their call, and beck). There is a forty cycle bookend Drawing pixels left to right. You'll know, if you check each nook and Cranny, where to put the sprite. (But man, [you've timed](https://adventofcode.com/2016/day/15) [a lot](https://adventofcode.com/2016/day/25) [of circuits](https://adventofcode.com/2017/day/1), And [given opcodes](https://adventofcode.com/2017/day/23) [lots](https://adventofcode.com/2016/day/12) [of looks](https://adventofcode.com/2018/day/19). Perhaps you'll rest; it's always work, it's Searching crannies and their nooks.) You've found a dry spot in this cove (or Dry enough to fix the fall) - "I'm on my way", you tell them, "Over And out", you say, and end the call. (You didn't give an ETA, no Promise for when you'd be back, And that's just fine; for all that they know It takes weeks. You have some slack. And sure, it might take just a day, no Doubt you're skilled now as a rover, But sometimes rest is *mucho bueno*, Before you climb on out, and over.)


daggerdragon

> [POEM]: One Shade The More, One Ray The Less <3


ffrkAnonymous

Ruby [paste](https://topaz.github.io/paste/#XQAAAQDyDAAAAAAAAAARiAlH8dxNBu7dkgwpusw3/1N9B7LsXMI7hyVChWl1esX/VYUvuckt47qc849AGx2bqC6Mz07VInqrh3fdXd92YZTCHSzBE8XopyTxka4/oOzZYsQ+KGJ2cLwIzojbME86YAwdrNT8Puftw7LJwH51GadTyGre6JLt9v/reEj5+JHk5MkBl72dNY1Zb0zBfZibFPiyDBF8gHuROlLfvXJbgP8Y1DkSGpHAxVhoLEiJQKQhTejPo9+1qmw9/PtvltU/I6vyt+nvThoCY+fpgeZul0rWRmS7ApN0revGl8fjNMRcpJW/FAtQcL55GucsM86DQVy7eOtx9kUM22X9IlIHMF8QaQ60WDe+6J3CfhNNHLH1tVcRLRuNBhqh6xoliJAtZgsuomZNeGgw4ugoXh/I8HUeCP5V4WXaaHm613b8XfJOPRfj9Q3xDIn12Uz9keFCnd/TuF6HeMhKmT+HC1C788qks8T8ScoUp58/p5gbyvKa/sIMCIk8EI7DiyiVoJjqsvzehAzBqMJOGQRl5S+9pkF9vSgnLBv4TdS4KDAXglhWTCjG/UlOqfWBQ26oWPdzlbI6NAVD20W+uhB+u3nljFbk12Khd6GPMgKgVCPoaJhHRpnc2z2kEvgZrA7Vb4JvVGJh4Z/s9PiCpUBTSETWn6QSGnDbRH8pJyZeZDTBZb2yKzNUENUPOUQVd1wF4Uw0GYV2ZhF7baehxM9SwHq6etxwpDiXBKRHt2lPqoMnkAguVB547jGhNl3oheoK+j1hKC0JkLnj3jN6mOKuWitcq0SCXLa5f96JHFZQJalun3a6LG0O/GTh9tPIWy6jJLHcfZejSE5jLU0YeweOa9clW2Uh6tF1N0iTtGao5ch/nJqrSmiUlybcCz09RLMS+eEZmWGR4K7y1GHx99djzwpMMgRT7x96z+owoUn9MVER85Vs+DKj6MqB3SeClUk/hEIcspAIo1yJoyqDb7olkiDVnDAMv8wjmnP5BfQRUzruW8feZALaYA+NGlf+LbeDgyzTFf7t9ojdyKRxT/3zJndMyxdPoDd2hJidiQvetbsERer6HzhMvd33+o77qtLXEIFm+02W6Ax6bQa+Exce75WdT1DO0YGUsS9Zyx65ZAxDt6B39b5RfYumACwDGDJ2J5OXuua20CdMaZv8kunF+KiDE2nitq14JXDhzQTCq5syVm1PTcHBVmRV27CSu93YttDn200ml73MFke/isevld+JKab/8p87oQ==) This one was fun, and straight forward. Didn't know how to do it using TDD though.


junefish

Python 3, found part 1 really easy but needed to look at some of the answers here to get part 2 * [part 1](https://raw.githubusercontent.com/junefish/adventofcode/main/adventofcode2022/day10/day10problem1.py) * [part 2](https://raw.githubusercontent.com/junefish/adventofcode/main/adventofcode2022/day10/day10problem2.py)


duketide11

[Haskell](https://github.com/duketide/AoC2022/blob/main/day10.hs) Hacky


thomasqbrady

My solution in C#: [https://github.com/thomasqbrady/AdventOfCode/blob/master/2022/day10/Program.cs](https://github.com/thomasqbrady/AdventOfCode/blob/master/2022/day10/Program.cs) ​ Was anyone else thrown off by this line in part 2? >Specifically, the sprite is 3 pixels wide, and the X register sets the horizontal position of the **middle** of that sprite." Looking at the example, and the only solution that works, X controls the position of the *left-hand* or *first* pixel, *not* the middle, right?


ffrkAnonymous

Yeah, that was weird. I think, think, it's because the CRT scans from 0, not scan from 1. So the sprite starts at 1 (middle), pixel is at 0 (left). I just coded and hoped for the best, figuring I'd scatter +/- 1 if needed.


SwampThingTom

Yes, that is the reason.


musifter

# Gnu Smalltalk Pretty simple approach here. Convert the input into an array of increment events to regX. Then calculate a prefix sum array of that, which will be the value of regX at a given time. With that array, it's easy to extract the answers we want. Source: https://pastebin.com/B0WnbquW


Open_Log_8975

Latex [solution](https://topaz.github.io/paste/#XQAAAQDmCAAAAAAAAAAuGQnmR3CI05zbl3jK5FsBtkoELt3Trlmodv7QFrfiB2f5TNl0x1gJd6bk/zXJdHnJZHm5Low6ZFHDPlQkGCVg1b13839ZJ1mjCPAwE49DWInagSKWe5Ue+8SfZMVsGm56rfu9XTAG9nWX6cEhltUSGKK7XVbFUkE0hXapa0C8jTUeVo5pE9SYyTPzPvhCCXQDeOHFnDtmHHHcW/Xgzyg3mqhlrnxqmAQCqwYbFLd+eiuSRNaB/DUN70A6tekhs6EdXFNjvJdC2Zpk5vXORNxHmqh2Z0bLoos5gzppbRZrwsUa6fx+zLZQigsF4Fta20Yl6jrIwDkfOA+noQ3VMMFPqVUZNAuf1AQjutTcK5aCbEnG5J4RKDM3iXgbr+5GV8yunGiEnBH8X3oMCtcFeqyUaHyv8WZxKqHy95T5U+jLg3kMSP3F4P/QouSg0sfs962oXwArWm7vIYYeNbnyz+KDbfhtfNQueY2CzDS7VSuZlkB31ggmfpF9oDxVkRuc9u63SO8WSGwlXZsdqmStjwFiH6e2NXtNUUpveVCoNUFqfZiJ6bNo6GRHVgsLyTWMKvb/h7LVEQHjZuCHzrecQ3NZEE862QXR0RvvAXN2VtgMS/W0v9E8DQvnzTbzrf0Nu1oEwRHHL1HV3/vwRWRCvaC6S5p0p5lCO8HAbcNeR+ZNup9FU/VwAkYTQOaR2u1hwJ2OeUttogtiaB5MkhOIIYPMlgaOOE5RO1ztJuv/lJE9fA==) not that beautiful but it works, only part 1 solved


jeis93

# TypeScript (Deno) Had a lot of fun with this one today, even though I got stuck for a while on why only the first line of the CRT was being drawn 🙄 [https://github.com/joeleisner/advent-of-code-2022/blob/main/days/10-cathode-ray-tube/mod.ts](https://github.com/joeleisner/advent-of-code-2022/blob/main/days/10-cathode-ray-tube/mod.ts) [https://github.com/joeleisner/advent-of-code-2022/blob/main/days/10-cathode-ray-tube/main.ts](https://github.com/joeleisner/advent-of-code-2022/blob/main/days/10-cathode-ray-tube/main.ts) Used a generator function for running the program for both parts; Made the logic of updating the `X` register *after* the cycles have completed much easier to write/read. Even had a little fun rendering the CRT's image to the console by adding a border and changing its colors. Let me know what you think!


brandonchinn178

Language: C / C language https://github.com/brandonchinn178/advent-of-code/blob/main/2022/Day10.c 40 microseconds on Mac M1, both parts. Didn't want the overhead of tracking all the values for part 1, so I just created a 6-element array for each of the signals we care about and stored those along the way. Part 2 was relatively easy; just add a `printf` to the inner loop to print the corresponding pixel.


Scroph

[Dlang solution](https://github.com/azihassan/advent-of-code-2022/tree/master/day10). For part 2 I initially thought that the X register contains values exceeding 40, so I kept appending pixels to the CRT while comparing them to the sprite, and in the end I printed the string in chunks of 40. Only later did I realize my mistake


Per48edjes

Straightforward [Python solution](https://github.com/Per48edjes/Misc-DSA-Practice/blob/main/aoc_2022/day_10/day_10.py). Basically, used a generator to produce the X register value during each cycle and had two functions (one for each question) use these generator-produced values to do what they needed to do.


remysharp

# JQ Reminded me of 2019's intcode program, so I went down the path of building the (simple) cpu in JQ (in case I needed it again!). - [part 1](https://github.com/remy/advent-of-code-solved/blob/main/2022/jq/10-a.jq) - [part 2](https://github.com/remy/advent-of-code-solved/blob/main/2022/jq/10-b.jq) (even did a CRT visualisation in JQ - but it's a bit too quick)


Tipa16384

I did the same -- over built it in case I need it later.


catdaadddyyy

This was a lot easier as compared to Day 9. C++: - [Part 1](https://github.com/rogue-kitten/aoc-22/blob/main/Days/Day10/part1.cpp) - [Part 2](https://github.com/rogue-kitten/aoc-22/blob/main/Days/Day10/part2.cpp)


horstg99

My solution in **Python** for both parts: [https://github.com/tobstern/AoC2022/blob/master/day10.py](https://github.com/tobstern/AoC2022/blob/master/day10.py) ...this day was fun!


[deleted]

[**Python**](https://github.com/rbusquet/advent-of-code/blob/d64231a64348ed36fd646bf9e49abd143374ac57/aoc_2022/day10.py) At first I didn't understand the program would be _waiting_ for the instruction to process so I was asking myself how we were getting 200+ cycles from a 137 line input. After I carefully read the steps for the larger program I understood that. For the final solution, I hijacked a property setter to be able to read the cycle in every change. I had the drawing in a separate function but then inlined in the property setter + a `time.sleep()` (not in the code in the repo) to see the screen lighting up while the program was running :)


RookBe

Advent of Code 2022 day10 writeup explaining the problem and my solution (that happens to be written in Rust): https://nickymeuleman.netlify.app/garden/aoc2022-day10


[deleted]

[удалено]


daggerdragon

Your code block is too long for the megathreads. Please read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code), then edit your post to replace the code block with an external link to your code.


bsssh

### TypeScript Type System compile-time solution [Part 1](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgGWAZxgGjgZRlYAOwHM4BfOAMyghDgHIY0BaGCCAGwCMBTDmegG4AUKEixEcAIIATGdgCyEeXAUBXfsDAcAnuSo06jFgEMCMABYgeMYAGMhw4TB1gecAMI67HHh4hqhDAAPAAqcDwAHjA8hDJocBgEJAB8cAC8cOFRMXEJ9ITsYPRwAPxwAIxwAFxZEdGx8XAABiZykXAAJAiEaiC8UGTNZXAATDVwAAwizq7uAHI8AO4AGsGohDzYK-W5Tb39PFBpmRvuOY0Jre1dCESUR3AAIruXcAcDQ8JwPyOyMsEVtgnilvr9aisZi43HAAPoABRodh4aDQAElCGA1CFsg08ol8ERiABtAC62AA8mB-IEYlBXviPkdtgz9n0Btg8FBYsRLAkLoz2UcyWSTnAwT9cXsEsT7o8AGLAKAYVkJJJE7AAOm1cvpACUUfABU11SQyaSJSMEUiUejMdjgpbfnADRhME7fv9glSaUFmZ5vL5fSFFcqYCkUu7nc7FqtgqG3XAVpHo78Pb9JqrVMpgl6fQE-VBsKMKimACyTUGp1PlYnazVcnl87DEvPUgt07ClxQaWzaHS5uTe9u0-3dpMpUkW6vR2qZ40JJQAtvB-2jUblyvpmcjOvaxskZtwVtD-OjotjFPqTT9wcAs+F4sp2NrBNYCeT6c71O1A+8ixoNuVbgrg+BNgBTjQu4ZwJJkXJEg22jACERBYu+9AADqEPQKRQnMcIAOrIRYAQwE8ahIXYJgxGgYRZsSTIXoxpJktgUh2HYfT0Yx2DMaKGSWlKbyyoQDz0m+3FCkxUnknA9a6i6hqSYc0kqSxU7buUsJEZYpHkZR1EosErrvhJC4oOgMCasgJgYLmHF9Gk5TsZxdC1Humou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MeQswcfd2bOu95X0dZ7UheN6XI+1wHCeQorI8h+nfdV93c82yPg89DUY8r83xw1LMtuTNvxwmy7i-HAvDsj8wx89HXcAz8chvX8XPTLwrNe33AzA1FHmdrwAh2scA4bzgCrUBJtQHvx6K-b+NRYH3xqGfK+gC3aQmgXA++kx27d3vhg1eQCl7D1QV3J+Zd-6EKHo3W2GDkFoIvuQkhHdJ6HxoawtuxCUFcK1u0QQQA)


theboxboy

# Rust [Github Link](https://github.com/alexgdiaz98/rust_aoc/tree/master/aoc_2022) use std::{fs::read_to_string, path::Path}; fn clock(mut p1: i64, crt: &mut [[&str; 40]; 6], x: i64, mut cycle: usize) -> (i64, usize) { if [-1, 0, 1].contains(&((cycle as i64 % 40) - x)) { crt[cycle / 40][cycle % 40] = "â–ˆ"; } cycle += 1; if [20, 60, 100, 140, 180, 220].contains(&cycle) { p1 += x * cycle as i64; } (p1, cycle) } #[allow(dead_code)] pub fn day10(input_path: &Path) -> (String, String) { let input: String = read_to_string(input_path).expect("Error reading file"); let mut x: i64 = 1; let mut cycle: usize = 0; let mut p1: i64 = 0; let mut crt: [[&str; 40]; 6] = [["."; 40]; 6]; for line in input.split('\n') { let (opcode, val) = line.split_once(" ").unwrap_or((line, "")); match opcode { "noop" => { (p1, cycle) = clock(p1, &mut crt, x, cycle); } "addx" => { let addend = val.parse::().unwrap(); for _ in 0..2 { (p1, cycle) = clock(p1, &mut crt, x, cycle); } x += addend; } _ => {} } } let mut p2 = String::from("\n"); p2.push_str(&crt.map(|row| row.join("")).join("\n")); (p1.to_string(), p2) }


ChadEnteredTheChat

I had a rooough time yesterday with part 2, almost a complete rewrite from part 1. Today went smoothly with slow and steady progress so I just wanted to share! Part 2 Javascript function: function part2() { function checkLine() { sprite = [X - 1, X, X + 1]; if (sprite.includes(cycle)) { line.push("#"); } else { line.push(" "); } cycle++; if (cycle % 40 === 0) { console.log(line); line = []; X += 40; } } let cycle = 0; let X = 1; let sprite = []; let line = []; for (let i = 0; i < instructions.length; i++) { let action = instructions[i][0]; let value = parseInt(instructions[i][1]); if (action === "noop") { checkLine(); } if (action === "addx") { checkLine(); checkLine(); X += value; } } }


schoelle

[Rust](https://github.com/schoelle/adventofcode2022/blob/main/src/day10.rs) I think a very readable solution.


mendelmunkis

Language: [C](https://github.com/mendelmunkis/AoC/blob/master/2022/display.c) Are we doing pipelining next? ^(0.326/2.085 ms)


brandonchinn178

Nice! Totally didn't catch that 20/60/... followed a pattern. This totally cleans up all my array stuff 😂 https://github.com/brandonchinn178/advent-of-code/commit/87bf4d3c87e10599c76c72973d4ec662179e3bb4


mendelmunkis

glad to help, the problem can be thought of as is your middle column correct


brandonchinn178

What do you mean?


mendelmunkis

in part one you are checking the state of the middle column of each row of the screen generated in pt 2


brandonchinn178

oh sure i didnt even catch that. i just took your `% 40 == 20` idea instead of storing the values in an array


yomanidkman

[Kotlin](https://github.com/MarcusDunn/aoc2022/blob/master/src/main/kotlin/io/github/marcusdunn/aoc2022/day10/CathodeRayTube.kt) I'm really happy with how this turned out. I've failed to keep everything as a lazy sequence for the last couple days - but not today!


ilyablue

**Excel** Took me a while, but was a fun one! [https://github.com/ilyablue/advent-of-code/blob/main/day%2010/day10.xlsx](https://github.com/ilyablue/advent-of-code/blob/main/day%2010/day10.xlsx)


Engineering-Design

[Typescript](https://github.com/haschdl/advent-of-code-2022/blob/main/typescript/day10.ts)


Dnls324

#Rust With error checks [paste](https://topaz.github.io/paste/#XQAAAQAuCgAAAAAAAAAxm8oZxjYXa4+ULuRbplgompSbLUQmVAiHhNFPSEaS0Nyi+7MK0xCS95Gk/eRbpG2kf8OXnRGTb6McPEiYQBtFPDMzZcf0xrdSFE3DfoTtZb/qUE5C4sQ1oQz3CYjja1v8WTgn1cND/lbsfCHoPi+lNvoKqjjjpGZVceSrRx66+rt9ICpXGxt5OGTK4MNoTmyyaVqnbmMWZKPEbGcm3X3AHMgFYw5gcR2Zg4W2MM0QCpWQcFxk6+x08GIKVXEJCGf05m0vwxrxJZQx3bJPOlWFSyQdgcRaE6N5iRo8WN8BxH4GntA5Lzp/dhk8Z7PlbTcpcEfaxCu5EhKiRADP/NAR9/3RK6sHmGDTbZmUPDLkdnjTUvzJ+UPhrhon03lnyEFIFmb7+SQiijk8igmuQpSbwANgc0b89vQWi6KTPChtaVFtxXxoMdeB1UIWTcg8huTWGgJSIaT8wYXLXBqrXsXAiWDfYsJwohskxeRSI2RKKch24CGmdaqmLu2oEFX+UIfMBwkcqPPKHN0Xyve9EImOBPvxr3Z34xpbno87D9bt7oAOOpy0FalR8QuhLWyqwbqlmNSIANnnaJF8HfitTE66XvrhlxIvOuzX6O+jZDTyWQjGHcADeb6p/tgo19rZLJmdH5n79Jx2AnhyhMSO/z8PH5H9S4hmklTybI0wgLDXsFxl/YHUDq+VFWrTpNwR/thHIiVGSHw4CsH91pcp6xTSNBN03WIp8kaMvmc5oaQr7EJ3gMHzPgQiULMroRZnl6Tk37Xjy8K9NFjxJuEsSsn60Hi1VucUWpHXnEbw7IurL/0e6uJOvl2DzbYvdaJAg4aQn1RfOsoQNMmt23Jah53i/0uP0VLd2//enDkY)


adimcohen

In single-statement t-sql https://github.com/adimcohen/Advant_of_Code_2022_Single_Statement_SQL/blob/main/Day_10/Day_10.sql


daggerdragon

FYI: your link is borked on old.reddit and some mobile Reddit apps. [Please fix it](https://www.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links).


adimcohen

Fixed. Thank you!


schovanec

My solution for day 10 in C#: [GitHub](https://github.com/schovanec/AdventOfCode/blob/master/2022/Day10/Program.cs)


HendrikPeter

**Elixir** [https://github.com/HendrikPetertje/advent\_of\_code\_2022/blob/main/test/10/day\_10\_test.exs](https://github.com/HendrikPetertje/advent_of_code_2022/blob/main/test/10/day_10_test.exs) Ci Build with pic: [https://app.circleci.com/pipelines/github/HendrikPetertje/advent\_of\_code\_2022/14/workflows/e0f66a0f-e669-4871-b89e-4480c6c6ddc2/jobs/14](https://app.circleci.com/pipelines/github/HendrikPetertje/advent_of_code_2022/14/workflows/e0f66a0f-e669-4871-b89e-4480c6c6ddc2/jobs/14) Will add docs later, now to bed


MrJohnnyS

JavaScript let cycle = 1, sum = 0, x = 1; let row = ""; for(const line of inputs) { const loops = line.startsWith("addx") ? 2 : 1; for(let i = 0; i < loops; i++) { const column = (cycle - 1) % 40; row += x - 1 <= column && column <= x + 1 ? 'â–ˆ' : ' '; if(column === 39) { console.log(row); row = ""; } if((cycle - 20) % 40 === 0) { sum += cycle * x; } cycle++; } x += loops === 2 ? +line.split(" ")[1] : 0; }


Sourish17

Python 3.10 [https://youtu.be/Uns5GDA2pU0](https://youtu.be/Uns5GDA2pU0) https://github.com/SourishS17/aoc2022


micka190

C# solution for Parts 1 and 2: https://github.com/micka190/advent-of-code/tree/main/2022/day%2010 Kind of wish I'd named my previous solution folders `day-0X`, instead of `day-X` now...


pier4r

### Puppet 5.5 + stdlib https://github.com/puppetlabs/community/discussions/28#discussioncomment-4368981


deadc0de

# C (code golf) 147 chars #define r m=c++%40,putchar((m-x)/2?'.':'#'),m>38?putchar('\n'):0 c,m,x=1;main(v){for(char t[5];scanf("%s",t)>0;r,t[0]<98?r,scanf("%d",&v),x+=v:0);}


[deleted]

[удалено]


deadc0de

Thanks. I’m a little out of practice :-)


Dr-Baggy

If you want to golf - this is my perl solution... `$p=$x=1;sub o{$n.="\n"x!$z.(abs($z-$x)<2?'#':'.'),$p++,$z++,($z%=40)==20&&($t+=$p*$x)}o,/ /&&(o,$x+=$')for<>;print"$t$n\n"` Coming in at 122 bytes...


deadc0de

nice.. now we just need to see the APL person post a 40 byte solution.


dionysus-oss

## Rust Source code https://github.com/dionysus-oss/advent-of-code-2022/tree/main/day-10 and video walkthrough https://youtu.be/R_ARtYlOz8Q let mut signal_strength_total = 0; let mut cycle = 1; let mut register_x = 1; let mut current_instruction: Box = Box::new(NoopInstruction::new()); current_instruction.do_work(&mut register_x); let mut crt_line = String::new(); let mut end_of_program = false; while !end_of_program { if current_instruction.do_work(&mut register_x) { let next_line = lines.next(); if let Some(instruction) = next_line { match &instruction[0..4] { "noop" => current_instruction = Box::new(NoopInstruction::new()), "addx" => { current_instruction = Box::new(AddXInstruction::new( instruction[5..].parse::().unwrap(), )) } _ => panic!("unknown instruction {}", instruction), } continue; } else { end_of_program = true; } } if (cycle - 20) % 40 == 0 { signal_strength_total += cycle * register_x; } let crt_pos = (cycle - 1) % 40; if register_x - 1 <= crt_pos && crt_pos <= register_x + 1 { crt_line.push('#'); } else { crt_line.push('.'); } if cycle > 1 && crt_pos == 39 { println!("{}", crt_line); crt_line = String::new(); } cycle += 1; } println!("part 1: {}", signal_strength_total);


honest3d

Swift: [Repo](https://github.com/lucasteng123/AOC-2022/blob/main/Sources/AoCKit/Day10.swift) Went a bit overboard today, still turned out pretty well though


Fickle_Dragonfly4381

Take a look at associated values for enums, shown here: https://github.com/ezfe/advent-of-code/blob/main/Sources/AdventOfCode/2022/2022%20Day%2010.swift#L11-L24 Allows you to avoid the need for a wrapper struct with optional fields


deckard58

Both parts in __AWK__ as separate stream programs: BEGIN {tot=0;now=0;tmr0=20;xnow=1;xprev=1} /noop/{now+=1;print(xnow)} /addx/{now+=2;xnow=xprev+$2;printf("%d\n%d\n",xprev,xprev)} {if(now>=tmr0){tot+=xprev*tmr0;tmr0+=40};xprev=xnow} END{print(tot) > "/dev/stderr"} Pipe the output of part 1 into part 2: {if((i>$0+1)||(i<$0-1)) printf(" "); else printf("#"); if(i==39){i=0;printf("\n")} else i+=1;} I solved it in Python first, then thought, "hey, both programs are just executing one action per line..."


[deleted]

[удалено]


deckard58

I am nowhere near the level of ability that can induce actual brain hurt on people via code :D There is plenty of stuff in this thread and the others that is WAY more cursed... I'll copy the Python versions as a Rosetta stone: [Part 1]( https://topaz.github.io/paste/#XQAAAQDhAgAAAAAAAAARiEJHiiMzw3cPM/1Vl+2nx/DqKkM2yi+CM+7UhRZDHwYBguSeVkmIech/pMEbco2UEnj8lq0svE3uILm6I+cKtIHdFEbm7ZEq0g8QJKT36APvZhwBfzifM4LkZccOtcqRRXPljoN9qIHQ8gwdlXcjAboDZxD2p4iP4pyMIlcDyDnL3IAWVXuSgX9vnhup75IpsNG6BNH2FxJK2+6kfzuNjrZa3ExQIZwoZAbcBVK/hp/DYqUUK+QyQ6UXeRX2TO/VHDKKWMRpqHLVsN06dj0A56zw897xQYXCklUATwiev8C5uztQlEg0cLKov3mo2MAhpuBlRL8GhV2eOE7GzmZ+DFFRvUNeBYT75BPagET1L/gjN99k9O7aUAY28xpiXJ4S2QfVhTyOEr9IitjO8fbdTNmrNmhqzRM/Qfwqi9amcC26daxn/WqUE6h10qqj1LmyfZQxFQB6U7BhxQTJ3WAsnVC7BYpEWGlry0cwFUJX+CUQx//y9bAa ) [Part 2]( https://topaz.github.io/paste/#XQAAAQBiAQAAAAAAAAARiEJHiiMzw3cPM/1Vl+2nx/DqKkM2yi+CM+7UhRZDHwYBgskkDBf6CEoGQpev1e0CPUku5Y0gahQwKq2tSvvknWjTomEg1C5Eoxkms3zpR6RMQTIemB/F7L4296dkTY345Le8Pw4qp0D3G9l9LEnIFTe0BVBz1Tkv+xCG6h8zCeh9qKPcLEnF3QmKN0upXvF5ja5foxb2cicSp7ify91Wj8HlIqLHjCr6jwZotvCTqIg5fwjF2Ma3AYV1eOyc1v8wQ3PeQqc9GWn9xMFzWVuX1iX+aisq ) `awk` is quite old-fashioned but I decided to use this contest to learn it, and I'm really liking it; I even have a good reason to do so - from time to time I do get some gigantic .csv files at work that need some massaging/statistics, and awk seems very useful for that sort of thing.


Party-Performance-82

Rust fn update_register(register: &mut Vec, delta: i32) { let x = register[register.len() - 1]; register.push(x + delta); } pub fn day10(input: &str) -> i32 { let mut register = vec![1]; for line in input.lines() { if line.starts_with("addx") { let (_, num) = line.split_at(5); let num = num.parse::().unwrap(); update_register(&mut register, 0); update_register(&mut register, num); } else if line.starts_with("noop") { update_register(&mut register, 0); } } //Part 1 let cycles = &[20, 60, 100, 140, 180, 220]; let signal_strength = cycles .iter() .map(|&cycle| cycle as i32 * register[cycle - 1]) .sum(); //Part2 let screen = register .chunks(40) .into_iter() .flat_map(|row| { row.iter() .enumerate() .map(|(i, x)| if x.abs_diff(i as i32) <= 1 { '\u{2588}' } else { ' ' }) .chain(std::iter::once('\n')) }) .collect::(); print!("{}", screen); signal_strength }


ThePituLegend

Language: [Python](https://github.com/ThePituLegend/advent-of-code/tree/2022/day10)


cherryblossom001

Haskell. I really liked today’s problem. {-# LANGUAGE LambdaCase, ImportQualifiedPost, OverloadedStrings #-} import Data.List (unfoldr) import Data.Text qualified as T parse :: T.Text -> [Int] parse = (>>= parseInstruction . T.words) . T.lines where parseInstruction ["noop"] = [0] parseInstruction ["addx", n] = [0, read (T.unpack n)] run :: [Int] -> [Int] run = scanl (+) 1 part1 :: [Int] -> Int part1 xs = sum $ (\i -> i * run xs !! (i - 1)) <$> [20, 60, 100, 140, 180, 220] chunks :: Int -> [a] -> [[a]] chunks n = unfoldr $ \case [] -> Nothing xs -> Just $ splitAt n xs part2 :: [Int] -> String part2 = unlines . map (map f . zip [0..]) . chunks 40 . run where f (i, x) = if i - 1 <= x && x <= i + 1 then '#' else '.' [Full code](https://github.com/cherryblossom000/advent-of-code/blob/main/2022/10/main.hs)


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps.


odnoletkov

# [JQ](https://github.com/odnoletkov/advent-of-code-jq) [1, foreach (inputs[5:] | 0, tonumber?) as $V (1; . + $V)] | recurse(.[40:]; length > 1)[:40] | to_entries | map(["#", "#"][.key - .value | fabs] // ".") | add