#!/bin/env ruby require 'pry' lights = File.readlines('./input').map(&:chomp).map(&:chars) @light_grids = [Marshal.load(Marshal.dump(lights)), Marshal.load(Marshal.dump(lights))] @grid_size = lights.count runs = 100 @part2 = false def animate(char, x, y, grid_num) if @part2 case [x, y] when [0, 0] return '#' when [0, @grid_size - 1] return '#' when [@grid_size - 1, 0] return '#' when [@grid_size - 1, @grid_size - 1] return '#' end end neighbors = [] (x - 1).upto(x + 1) do |x_pos| next if x_pos < 0 or x_pos >= @grid_size (y - 1).upto(y + 1) do |y_pos| next if y_pos < 0 or y_pos >= @grid_size next if x_pos == x and y_pos == y # puts "#{grid_num},#{x_pos},#{y_pos}" neighbors.push(@light_grids[grid_num][x_pos][y_pos]) end end on_neighbors = neighbors.count('#') if char == '#' if [2, 3].include?(on_neighbors) '#' else '.' end elsif on_neighbors == 3 '#' else '.' end end def print_grid(grid) grid.each { |line| puts line.join } end @light_grids.cycle(runs / 2).with_index do |grid, i| current_grid = i % 2 # References the current light grid next_grid = current_grid == 1 ? 0 : 1 # puts "this grid: #{current_grid}, next grid: #{next_grid}" grid.each_with_index do |line, x| line.each_with_index do |char, y| @light_grids[next_grid][x][y] = animate(char, x, y, current_grid) end end end puts @part2 == true ? "Part 2 Solution: #{@light_grids[0].flatten.count('#')}" : "Part 1 Solution: #{@light_grids[0].flatten.count('#')}" # binding.pry