Решение на Шеста задача от Здравко Стойчев

Обратно към всички решения

Към профила на Здравко Стойчев

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 18 успешни тест(а)
  • 0 неуспешни тест(а)

Код

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

Лог от изпълнението

..................

Finished in 0.41424 seconds
18 examples, 0 failures

История (1 версия и 0 коментара)

Здравко обнови решението на 15.12.2011 13:53 (преди над 8 години)

+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