Николай обнови решението на 18.12.2011 15:49 (преди около 13 години)
+module GameOfLife
+ class Board
+ include Enumerable
+
+ attr_accessor :cells
+
+ def initialize(*args)
+ @cells = args.uniq
+ end
+
+ def neighbours(x, y)
+ [[x-1, y-1], [x-1,y], [x-1,y+1], [x,y+1], [x,y-1], [x+1,y+1], [x+1,y-1], [x+1,y]]
+ end
+
+ def [](x, y)
+ cells.find {|cell_x, cell_y| x == cell_x && y == cell_y} != nil
+ end
+
+ def should_live(x, y)
+ live_neighbours = neighbours(x, y).select {|x, y| self[x, y]}.count
+ self[x,y] ? (2..3) === live_neighbours : 3 == live_neighbours
+ end
+
+ def each
+ cells.each {|x, y| yield x, y}
+ end
+
+ def next_generation
+ all_cells = cells.map {|x, y| neighbours x, y}.inject(cells, :+).uniq
+ Board.new *all_cells.select {|x, y| should_live(x, y)}
+ end
+ end
+end