Николай обнови решението на 20.12.2011 23:19 (преди около 13 години)
+module GameOfLife
+
+ class Board
+ include Enumerable
+
+ def initialize(*args)
+ @cells = args
+ end
+
+ def [](x, y)
+ @cells.include? [x, y]
+ end
+
+ def each
+ @cells.each { |x| yield x}
+ end
+
+ def count
+ @cells.count
+ end
+
+ def next_generation
+ BoardProcessor.new(*@cells).process
+ end
+
+ def kill_cell(cell)
+ @cells.delete cell
+ end
+
+ end
+
+ class BoardProcessor
+
+ def initialize(*cells)
+ @board = Board.new *cells
+ @new_board = []
+ end
+
+ def neighbours(cell)
+ x = cell[0]
+ y = cell[1]
+ neighbours_list = [[x - 1, y + 1], [x, y + 1], [x + 1, y + 1], [x - 1, y], [x + 1, y]]
+ neighbours_list += [[x - 1, y - 1], [x, y - 1], [x + 1, y - 1]]
+ end
+
+ def process
+ @board.each { |cell|
+ process_cell cell
+ }
+ Board.new *@new_board
+ end
+
+ def process_cell(cell)
+ neighbours_list = neighbours cell
+ num_life_neighbours = alive_neighbours neighbours_list
+ apply_rules cell, num_life_neighbours
+ grow_cells neighbours_list
+ end
+
+ def apply_rules(cell, num)
+ if num >= 2 and num <= 3 then @new_board << cell end
+ end
+
+ def alive_neighbours(list)
+ list.select { |cell| @board[cell[0], cell[1]] }.count
+ end
+
+ def grow_cells(list)
+ list.each { |cell|
+ if (alive_neighbours cell) >= 3 then @new_board << cell end
+ }
+ end
+
+ end
+
+end