Георги обнови решението на 15.12.2011 17:15 (преди около 13 години)
+module GameOfLife
+ class Generator
+ def self.next_generation(board)
+ Board.new(*board.select{ |x,y| board.live_neighbours_count(x,y).between?(2,3)} +
+ board.map{ |x,y| board.dead_neighbours(x,y)}.inject([],&:|).
+ select{|x,y| board.live_neighbours_count(x,y) == 3})
+ end
+ end
+
+ class Board
+ include Enumerable
+
+ def initialize(*initial_values)
+ @cells = initial_values.uniq
+ end
+
+ def [](x,y)
+ return @cells.index([x,y]) != nil
+ end
+
+ def each
+ @cells.each do |pair|
+ yield pair
+ end
+ end
+
+ def get_neighbours(x,y)
+ [[x-1, y+1], [x, y+1], [x+1, y+1],
+ [x-1, y], [x+1, y],
+ [x-1, y-1], [x, y-1], [x+1, y-1]]
+ end
+
+ def live_neighbours_count(x,y)
+ get_neighbours(x,y).select{|x1,y1| self[x1,y1]}.length
+ end
+
+ def dead_neighbours(x,y)
+ get_neighbours(x,y).select{|x1,y1| not self[x1,y1]}
+ end
+
+ def next_generation
+ Generator.next_generation(self)
+ end
+ end
+end