Венета обнови решението на 19.12.2011 01:02 (преди около 13 години)
+module GameOfLife
+ class Board
+ include Enumerable
+
+ def initialize(*args)
+ @alive_cells = args.uniq.map do |cell_coordinates|
+ Cell.new(cell_coordinates, self)
+ end
+ end
+
+ def [](x, y)
+ any? { |cell_x, cell_y| cell_x == x && cell_y == y }
+ end
+
+ def each
+ @alive_cells.each do |cell|
+ yield cell.coordinates
+ end
+ end
+
+ def next_generation
+ new_generation_cells = stay_alive_cells + newborn_cells
+ eval "Board.new #{new_generation_cells.join ", "}"
+ end
+
+ private
+ def stay_alive_cells
+ @alive_cells.inject([]) do |alive_cells, cell|
+ alive_cells << cell.coordinates.to_s if cell.stay_alive?
+ alive_cells
+ end
+ end
+
+ def potential_newborn_coordinates
+ @alive_cells.inject([]) do |potential_newborns, cell|
+ potential_newborns += cell.dead_neighbours_coordinates
+ potential_newborns.uniq
+ end
+ end
+
+ def newborn_cells
+ potential_newborn_coordinates.inject([]) do |newborns, coord|
+ new_cell = Cell.new(coord, self)
+ newborns << new_cell.coordinates.to_s if new_cell.newborn?
+ newborns
+ end
+ end
+ end
+
+ class Cell
+ def initialize(coordinates, board)
+ @x, @y, @board = coordinates[0], coordinates[1], board
+ end
+
+ private
+ def neighbour_cells_coordinates
+ [[@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 neighbour_cells_statuses
+ neighbour_cells_coordinates.map { |coord| @board[coord[0], coord[1]] }
+ end
+
+ def alive_neighbours_count
+ neighbour_cells_statuses.inject(0) do |count, neighb_status|
+ count += 1 if neighb_status
+ count
+ end
+ end
+
+ public
+ def stay_alive?
+ (2..3).include? alive_neighbours_count
+ end
+
+ def newborn?
+ alive_neighbours_count == 3
+ end
+
+ def coordinates
+ [@x, @y]
+ end
+
+ def dead_neighbours_coordinates
+ neighbour_cells_coordinates.select do |coord|
+ !@board[coord[0], coord[1]]
+ end
+ end
+ end
+end
Този код изглежда много добре като цяло и докато го четох, направо ме застреляха някои WTF моменти, които хич не очаквах :) Бих желал да ти задам някои въпроси по него, пингни ме някое междучасие.
И след като крайният срок вече мина...
Board.new *new_generation_cells
Вместо този зъл eval
. Беше ми забавно, поне, спор няма :D