Решение на Шеста задача от Евгени Кунев

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

Към профила на Евгени Кунев

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
def initialize(*living_cells)
@alive = living_cells
end
def each
@alive.each { |cell| yield cell }
end
def [](x, y)
@alive.include? [x,y]
end
def next_generation
next_living = remain_alive + newborn
Board.new *next_living.uniq
end
def remain_alive
@alive.select do |cell|
neighbours = living_neighbours_count(cell)
2 <= neighbours and neighbours <= 3
end
end
def newborn
@alive.inject([]) { |potential, cell| potential + Board.neighbours(cell) }
.select { |cell| living_neighbours_count(cell) == 3}
end
def living_neighbours_count(cell)
Board.neighbours(cell).select { |cell| self[*cell] }.count
end
def self.neighbours(cell)
x, y = cell
[x - 1, x, x + 1].product([y - 1, y, y + 1]).reject { |cell| cell == [x, y] }
end
end
end

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

▸ Покажи лога

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

Евгени обнови решението на 16.12.2011 01:31 (преди около 13 години)

▸ Покажи разликите
+module GameOfLife
+ class Board
+ include Enumerable
+ def initialize(*living_cells)
+ @alive = living_cells
+ end
+
+ def each
+ @alive.each { |cell| yield cell }
+ end
+
+ def [](x, y)
+ @alive.include? [x,y]
+ end
+
+ def next_generation
+ next_living = remain_alive + newborn
+ Board.new *next_living.uniq
+ end
+
+ def remain_alive
+ @alive.select do |cell|
+ neighbours = living_neighbours_count(cell)
+ 2 <= neighbours and neighbours <= 3
+ end
+ end
+
+ def newborn
+ @alive.inject([]) { |potential, cell| potential + Board.neighbours(cell) }
+ .select { |cell| living_neighbours_count(cell) == 3}
+ end
+
+ def living_neighbours_count(cell)
+ Board.neighbours(cell).select { |cell| self[*cell] }.count
+ end
+
+ def self.neighbours(cell)
+ x, y = cell
+ [x - 1, x, x + 1].product([y - 1, y, y + 1]).reject { |cell| cell == [x, y] }
+ end
+ end
+end