Александър обнови решението на 20.12.2011 22:45 (преди около 13 години)
+module GameOfLife
+ class Board
+ include Enumerable
+
+ def initialize(*args)
+ @live_cells = args.uniq
+ @live_cells = [] if args == [[]]
+ @new_gen = []
+ end
+
+ def [] x, y
+ return true if @live_cells.include? [x, y]
+ false
+ end
+
+ def each
+ @live_cells.each do |x, y|
+ yield x, y
+ end
+ end
+
+ def count
+ @live_cells.count
+ end
+
+ def next_generation
+ @live_cells.each do |cell|
+ @new_gen << cell if (2..3).include? get_living_neighbours(cell).count
+ @new_gen |= get_dead_neighbours(cell).select {|c| get_living_neighbours(c).count == 3}
+ end
+ Board.new *@new_gen
+ end
+
+ def get_neighbours(cell)
+ [[cell[0]-1, cell[1]-1], [cell[0]-1, cell[1]], [cell[0]-1, cell[1]+1],
+ [cell[0], cell[1]-1], [cell[0], cell[1]+1],
+ [cell[0]+1, cell[1]-1], [cell[0]+1, cell[1]], [cell[0]+1, cell[1]+1]]
+ end
+
+ def get_living_neighbours(cell)
+ living_neighbours = []
+ get_neighbours(cell).each do |neighbour_cell|
+ living_neighbours << neighbour_cell if @live_cells.include? neighbour_cell
+ end
+ living_neighbours
+ end
+
+ def get_dead_neighbours(cell)
+ dead_neighbours = []
+ get_neighbours(cell).each do |neighbour_cell|
+ dead_neighbours << neighbour_cell if not @live_cells.include? neighbour_cell
+ end
+ dead_neighbours
+ end
+ end
+end