Борис обнови решението на 20.12.2011 04:04 (преди около 13 години)
+module GameOfLife
+ class Board
+ include Enumerable
+ attr_accessor :cells, :neighbours, :dead_cells
+
+ def initialize *cells
+ @cells = cells.uniq
+ @neighbours = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
+ @dead_cells = dead_neighbours
+ end
+
+ def next_generation
+ cells_new = @cells.dup
+ cells_new = apply_rules cells_new
+ Board.new *cells_new
+ end
+
+ def apply_rules cells_new
+ remained = @cells.select { |x, y| alive? x, y }
+ new = @dead_cells.select { |x, y| alive_count(x, y) == 3 }
+ remained + new
+ end
+
+ def alive? x, y
+ alive_count(x, y) == 2 || alive_count(x, y) == 3
+ end
+
+ def alive_count x, y
+ @neighbours.count { |i, j| @cells.include? [x+i, y+j] }
+ end
+
+ def dead_neighbours
+ dead = []
+ @cells.each do |x, y|
+ dead |= @neighbours.map { |i, j| [x+i, y+j] }
+ end
+ dead
+ end
+
+ def each(&block)
+ @cells.each(&block)
+ end
+
+ def [] (x, y)
+ @cells.include?([x, y]) ? true : false
+ end
+
+ def to_a
+ @cells
+ end
+
+ def count
+ @cells.count
+ end
+ end
+end