Красимир обнови решението на 16.12.2011 00:35 (преди около 13 години)
+module GameOfLife
+
+ class Board
+ include Enumerable
+
+ attr_accessor :board, :living_cell, :next_board
+
+ def initialize(*cells)
+ @board, @living_cell = {}, []
+ cells.each do |cell|
+ @board[[cell[0],cell[1]]] = true
+ @living_cell.include?(cell)? next : @living_cell << cell
+ end
+ end
+
+ def [](x, y)
+ board[[x, y]] ? true : false
+ end
+
+ def each(&block)
+ living_cell.each(&block)
+ end
+
+ def next_generation()
+ next_board = NextBoard.new(living_cell)
+ next_population = next_board.next_living_cells().uniq
+ Board.new(*next_population)
+ end
+
+ end
+
+ class NextBoard
+
+ attr_accessor :next_living_cells, :living_cells, :dead_cells
+
+ def initialize(living_cell)
+ @living_cells = living_cell
+ @next_living_cells, @dead_cells = [], []
+ find_dead_cells()
+ find_population()
+ end
+
+ def find_population()
+ continue_living()
+ reborning()
+ end
+
+ def reborning()
+ @dead_cells.each do |cell|
+ if (alive_neighbors(cell[0],cell[1]) == 3)
+ @next_living_cells << cell
+ end
+ end
+ end
+
+ def continue_living()
+ @living_cells.each do |cell|
+ if ((alive_neighbors(cell[0], cell[1]) == 2) || (alive_neighbors(cell[0], cell[1]) == 3))
+ @next_living_cells << cell
+ end
+ end
+ end
+
+ def neighbors(x, y)
+ [[x-1, y], [x+1, y], [x, y+1], [x, y-1], [x+1, y+1], [x+1, y-1], [x-1, y+1], [x-1, y-1]]
+ end
+
+ def dead_neighbors(x, y)
+ neighb = neighbors(x, y)
+ dead_neighbors = neighb - living_cells
+ dead_neighbors ? dead_neighbors : []
+ end
+
+ def alive_neighbors(x, y)
+ neighb = neighbors(x, y)
+ (neighb & living_cells).count
+ end
+
+ def find_dead_cells()
+ living_cells.each do |cell|
+ dead_neighbors(cell[0], cell[1]).each do |neighb|
+ @dead_cells << neighb
+ end
+ end
+ end
+
+ end
+end