1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Grid < Struct.new(:state)
  def next
    state_ = Array.new(100) {|x| Array.new(100) {|y|
      light = self.state[x][y]
      neighbors = self.neighbors(x,y).count(?#)
      (light == ?#) ? (([2,3].include?(neighbors)) ? ?# : ?.) : ((neighbors == 3) ? ?# : ?. )
    }}
    state_[0][0] = ?#
    state_[0][99] = ?#
    state_[99][0] = ?#
    state_[99][99] = ?#
    Grid.new(state_)
  end

  def neighbors(x,y)
    (-1..1).flat_map {|i| (-1..1).map {|j| [x+i, y+j] }}
           .reject {|ij| ij == [x,y] }
           .select {|i,j| (0..99).cover?(i) && (0..99).cover?(j) }
           .map {|i,j| self.state[i][j] }
  end

  def to_s
    self.state.map {|i| i.join }.join("\n")
  end
end

grid = Grid.new(DATA.read.split("\n").map {|i| i.split(//) })
100.times do
  grid = grid.next
end
puts grid.state.map {|x| x.count(?#) }.inject(:+)

__END__