Камен обнови решението на 20.12.2011 17:02 (преди около 13 години)
+
+module GameOfLife
+
+ class Board
+ include Enumerable
+
+ def initialize(*alive_coordiantes)
+ flatten_array = alive_coordiantes.flatten
+ @board = []
+ (0..(flatten_array.length-2)).step(2) do |i|
+ @board.push( [flatten_array[i],flatten_array[i+1]] )
+ end
+ end
+
+ def [](x,y)
+ @board.index([x,y]) == nil ? false : true
+ end
+
+ def each(&block)
+ @board.each(&block)
+ end
+
+ def alive_nbours(x, y)
+ neigbours = [[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]]
+ neigbours.keep_if { |x,y| self[x,y] }
+ neigbours.count
+ end
+
+ # Returns every cell within the borders of our simulation.
+ # Every dead cell that is too far alway from the living cells
+ # on the infinite board can't change it's state.
+ def get_borders
+ x_array = @board.map { |x,y| x }
+ y_array = @board.map { |x,y| y }
+ borders = [x_array.min-1, x_array.max+1, y_array.min-1, y_array.max+1]
+ (borders[0] .. borders[1]).to_a.product (borders[2] .. borders[3]).to_a
+ end
+
+ def next_generation
+ next_gen = @board.select{ |x,y| (cnt = alive_nbours(x, y)) == 2 || cnt == 3 }
+
+ for x,y in get_borders do
+ if alive_nbours(x,y) == 3 && self[x,y] == false then next_gen.push [x,y] end
+ end
+
+ return Board.new(next_gen)
+ end
+ end
+
+end