Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.6 kB
5
Indexable
Never
let use_test_input = Deno.args.join('').match(/test/)?.[0]
let file = './input' + (use_test_input == "test" ? '.test' : '')

let part_1_or_2 = Deno.args.join('').match(/\d/)?.[0]

let input;
input = await Deno.readTextFile(file)
input = input.split('\n')

let cycles = 1
let register = 1
let signals = []
let multiplier = 1

let screen = new Array(6 * 40).fill('.')

input.forEach(line => {
  let op = line == 'noop\r' ? 'noop' : 'addx'
  let [_, number] = line.split(' ')
  number = parseInt(number)

  add_cycle(op, number)

  function add_cycle(op, addx_arg = 0, on_cycle_num = 1) {
    const row = Math.floor(cycles/40)
    const x_pos = (register + (row * 40))

    const draw_center = cycles-1 == x_pos 
    const draw_left = cycles-1 == x_pos - 1
    const draw_right = cycles-1 == x_pos + 1

    let does_a_pixel_light_up = draw_center || draw_left || draw_right
    if(does_a_pixel_light_up) screen[cycles -1] = '#'

    if(on_cycle_num == 2) {
      register = register + addx_arg
    }

    cycles = cycles + 1

    if(20 * multiplier == cycles && multiplier < 12) {
      signals.push({cycles, register, signal_strength: cycles * register})
      multiplier = multiplier + 2
    }
  
    if(op == 'addx' && on_cycle_num == 1) return add_cycle('addx', addx_arg, 2)
  }
})

let part1 = signals.reduce((acc, cur) => { return acc+cur.signal_strength}, 0)
let part2 = '\n' + screen.join('').match(/[\.#]{40}/g).join('\n')
let result = part_1_or_2 == '1' ? part1 : part2
console.log(
	`Part ${part_1_or_2} ${use_test_input ? 'Test ' : ''}Results: ` +
		'\x1b[33m%s\x1b[0m',
	result
)