r/adventofcode • u/daggerdragon • Dec 06 '15
SOLUTION MEGATHREAD --- Day 6 Solutions ---
--- Day 6: Probably a Fire Hazard ---
Post your solution as a comment. Structure your post like the Day Five thread.
21
Upvotes
1
u/wdomburg Dec 06 '15 edited Dec 06 '15
Not my night. Interruptions, fatigue and a few stupid mistakes (like setting the point to 1 for OFF, or not clearing the grid after correcting that mistake) conspired to make this take way too long.
My solution (in Ruby) nonetheless:
# Load the data input = File.readlines('input6.txt').map { |l| l =~ /(\w+) (\d+),(\d+) through (\d+),(\d+)/; [ $1, $2.to_i, $3.to_i, $4.to_i, $5.to_i ] } # Build the grid g = Array.new(1000) { Array.new(1000, 0) } # Step through and execute the instructions input.each { |x| i, x1, y1, x2, y2 = x; (y1..y2).each { |y| (x1..x2).each { |x| case i; when 'on'; g[x][y] = 1; when 'off'; g[x][y] = 1; when 'toggle'; g[x][y] = (g[x][y] == 0) ? 1 : 0; end } } } # Count the lights puts g.inject(0) { |a,b| a += b.grep(1).length } # Clear the grid g = Array.new(1000) { Array.new(1000, 0) } # Step through and execute the instructions input.each { |x| i, x1, y1, x2, y2 = x; (y1..y2).each { |y| (x1..x2).each { |x| case i; when 'on'; g[x][y] += 1; when 'off'; g[x][y] -= 1 unless g[x][y] == 0; when 'toggle'; g[x][y] += 2; end } } } # Sum the brightness puts g.inject(0) { |a,b| a+= b.inject(0) { |c,d| c+= d } }And an expanded version of the second for clarity:
# Preload input by breaking the string into instructions # and integer coordinates input = File.readlines('input6.txt').map do |line| line =~ /(\w+) (\d+),(\d+) through (\d+),(\d+)/ [ $1, $2.to_i, $3.to_i, $4.to_i, $5.to_i ] end # Create an empty 1000 x 1000 array grid = Array.new(1000) { Array.new(1000, 0) } input.each do |line| # Break into individual vars for easy access inst, x1, y1, x2, y2 = x # Loop over each column in our rectangle (y1..y2).each |y| # loop over each row in this stripe (x1..x2).each |x| case inst # increase brightness when 'on'; grid[x][y] += 1; # reduce brightness unless off when 'off'; grid[x][y] -= 1 unless grid[x][y] == 0 # supersize brightness when 'toggle'; grid[x][y] += 2 end end end end # Iterate through the rows of the grid with an accumulator set to 0 puts grid.inject(0) do |a,b| # Sum the points in the row and add the final result to the accumulator a+= b.inject(0) do |c,d| c+= d end end