Здравко обнови решението на 15.12.2011 13:53 (преди около 13 години)
+require 'set'
+
+module GameOfLife
+ class Board
+ include Enumerable
+
+ def initialize(*alive_cells)
+ @alive_cells = Set.new alive_cells
+ end
+
+ def [](x, y)
+ @alive_cells.include? [x, y]
+ end
+
+ def each(&block)
+ @alive_cells.each(&block)
+ end
+
+ def count
+ @alive_cells.count
+ end
+
+ def next_generation
+ Board.new *possible_children.select { |cell| will_live? cell }
+ end
+
+ def neighbors(cell)
+ displacements = [-1, 0, 1].repeated_permutation(2).to_a - [[0, 0]]
+ displacements.map { |dx, dy| [cell[0] + dx, cell[1] + dy] }
+ end
+
+ def count_alive_neighbors(cell)
+ neighbors(cell).count { |neighbor| self[*neighbor] }
+ end
+
+ def will_live?(cell)
+ alive_neighbors_count = count_alive_neighbors(cell)
+ (self[*cell] and alive_neighbors_count == 2) or alive_neighbors_count == 3
+ end
+
+ private
+
+ def possible_children
+ @alive_cells.flat_map { |cell| neighbors(cell) + [cell] }.uniq
+ end
+ end
+end