1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
lights = Hash.new {|h,k| h[k] = 0 }

instructions = { "turn on" => ->(intensity) { intensity + 1 },
                 "turn off" => ->(intensity) { intensity.zero? ? 0 : intensity - 1 },
                 "toggle" => ->(intensity) { intensity + 2 } }

regex = /(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)/
DATA.read.scan(regex).each do |instruction, x1,y1, x2,y2|
  min_x,max_x = [x1,x2].map(&:to_i).sort
  min_y,max_y = [y1,y2].map(&:to_i).sort

  instruction = instructions[instruction]
  (min_x..max_x).each do |x|
    (min_y..max_y).each do |y|
      lights[[x,y]] = instruction[lights[[x,y]]]
    end
  end
end

puts lights.values.inject(&:+)

__END__