Skip to content

Instantly share code, notes, and snippets.

@wconrad
Created December 15, 2015 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wconrad/b4f2a1dae823a18bbe68 to your computer and use it in GitHub Desktop.
Save wconrad/b4f2a1dae823a18bbe68 to your computer and use it in GitHub Desktop.
Advent of Code, day 6
#!/usr/bin/env ruby
# http://adventofcode.com/day/6
class Lights
def initialize
@lights = HEIGHT.times.map do
[false] * WIDTH
end
end
def change(x1, y1, x2, y2, &block)
(x1..x2).each do |x|
(y1..y2).each do |y|
@lights[x][y] = yield(@lights[x][y])
end
end
end
def num_lit
@lights.flatten.count(&:itself)
end
private
WIDTH = HEIGHT = 1000
end
COMMANDS = {
"turn on" => ->(on) { true },
"turn off" => ->(on) { false },
"toggle" => ->(on) { !on },
}
lights = Lights.new
File.open("input", "r") do |file|
file.each_line do |line|
raise unless line =~ /^(.*) (\d+),(\d+) through (\d+),(\d+)$/
command, x1, y1, x2, y2 = $~.captures
x1 = Integer(x1)
y1 = Integer(y1)
x2 = Integer(x2)
y2 = Integer(y2)
lights.change(x1, y1, x2, y2, &COMMANDS.fetch(command))
end
end
puts lights.num_lit
#!/usr/bin/env ruby
# http://adventofcode.com/day/6
class Lights
def initialize
@lights = HEIGHT.times.map do
[0] * WIDTH
end
end
def change(x1, y1, x2, y2, &block)
(x1..x2).each do |x|
(y1..y2).each do |y|
@lights[x][y] = yield(@lights[x][y])
end
end
end
def total_brightness
@lights.flatten.reduce(&:+)
end
private
WIDTH = HEIGHT = 1000
end
COMMANDS = {
"turn on" => ->(brightness) { brightness + 1 },
"turn off" => ->(brightness) { [brightness - 1, 0].max },
"toggle" => ->(brightness) { brightness + 2 },
}
lights = Lights.new
File.open("input", "r") do |file|
file.each_line do |line|
raise unless line =~ /^(.*) (\d+),(\d+) through (\d+),(\d+)$/
command, x1, y1, x2, y2 = $~.captures
x1 = Integer(x1)
y1 = Integer(y1)
x2 = Integer(x2)
y2 = Integer(y2)
lights.change(x1, y1, x2, y2, &COMMANDS.fetch(command))
end
end
puts lights.total_brightness
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment