Елена обнови решението на 17.12.2011 11:19 (преди около 13 години)
+module GameOfLife
+
+ class Board
+
+ include Enumerable
+
+ attr_accessor :board
+
+ def initialize(*args)
+ @board = args.uniq
+ end
+
+ def next_generation
+ new_board = @board.select { |cell| [2, 3].include? live_neighbours_count(cell) }
+ @board.each do |cell|
+ new_board += dead_neighbours(cell).select { |cell| live_neighbours_count(cell) == 3 }
+ end
+ Board.new *new_board.uniq
+ end
+
+ def [] cell_x, cell_y
+ @board.include? [cell_x, cell_y]
+ end
+
+ def each
+ @board.each { |cell| yield cell }
+ end
+
+ private
+
+ def live_neighbours_count cell
+ neighbours(cell).select { |cell| @board.include? cell }.count
+ end
+
+ def dead_neighbours cell
+ n = neighbours(cell).reject { |cell| @board.include? cell }
+ end
+
+ def neighbours cell
+ x, y = cell
+ ([x, x - 1, x + 1].product [y, y - 1, y + 1]) - [[x, y]]
+ end
+ end
+
+end