2015/06/script.rb

102 lines
1.7 KiB
Ruby
Raw Permalink Normal View History

2021-11-23 13:05:11 +01:00
#!/usr/bin/env ruby
require_relative '../common'
class LightGrid
def initialize(brightness = false)
@brightness = brightness
@grid = Array.new(1000) { Array.new(1000, 0) }
end
def parse(instructions)
instructions.each do |string|
instruction, from_x, from_y, to_x, to_y = string.match(/\A(.*) ([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)\z/).captures
klass = instruction_klass(instruction)
(from_x.to_i..to_x.to_i).each do |i|
(from_y.to_i..to_y.to_i).each do |j|
@grid[i][j] = klass.process(@grid[i][j])
end
end
end
@grid.flatten.sum
end
private
def instruction_klass(instruction)
if @brightness
case instruction
when "turn on"
Brightness::TurnOn
when "turn off"
Brightness::TurnOff
else
Brightness::Toggle
end
else
case instruction
when "turn on"
Simple::TurnOn
when "turn off"
Simple::TurnOff
else
Simple::Toggle
end
end
end
class Simple
class TurnOn
def self.process(value)
1
end
end
class TurnOff
def self.process(value)
0
end
end
class Toggle
def self.process(value)
value == 1 ? 0 : 1
end
end
end
class Brightness
class TurnOn
def self.process(value)
value + 1
end
end
class TurnOff
def self.process(value)
value > 0 ? value - 1 : 0
end
end
class Toggle
def self.process(value)
value + 2
end
end
end
end
class Day6 < Day
def part1
LightGrid.new.parse input
end
def part2
LightGrid.new(true).parse input
end
end
Day6.run