Иван обнови решението на 20.12.2011 21:16 (преди около 13 години)
+module GameOfLife
+ NEIGHBOURS = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]].freeze
+ WILL_LIVE = [3,12,13].freeze
+
+ class Board
+ include Enumerable
+
+ def initialize(*living)
+ @population = Hash.new(0)
+ living.each do |cell|
+ tap_neighbours(*cell) unless cell.length != 2
+ end
+ end
+
+ def tap_neighbours(cell_x, cell_y)
+ NEIGHBOURS.each { |other| @population[[cell_x + other[0], cell_y + other[1]]] += 1 }
+ @population[[cell_x, cell_y]] += 10
+ end
+
+ def each
+ @population.each_key do |cell|
+ yield(cell.flatten) unless @population[cell] < 10
+ end
+ end
+
+ def next_generation
+ should_live = @population.select do |cell, actual_neighbours|
+ WILL_LIVE.include? actual_neighbours
+ end.keys
+ Board.new *should_live
+ end
+
+ def [](*idx)
+ @population[[idx[0], idx[1]]] >= 10
+ end
+ end
+end