Решение на Шеста задача от Пламен Стоев

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

Към профила на Пламен Стоев

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
def initialize(*args)
@cells = args.uniq
end
def each(&block)
@cells.each &block
end
def [](x, y)
@cells.include?([x, y])
end
def next_generation
Board.new(*(@cells - dead_cells + born_cells))
end
private
def neighbours(x, y, arg_hash)
all_around = ((x - 1)..(x + 1)).to_a.product(((y - 1)..(y + 1)).to_a) - [[x, y]]
all_around.select { |neighbour| not (arg_hash[:alive] ^ self[*neighbour]) }
end
def filter_cells(cells, &block)
cells.select { |cell| yield neighbours(*cell, alive: true).size }
end
def dead_cells
filter_cells(@cells) { |neighbour_count| not (2..3).include?(neighbour_count) }
end
def born_cells
empty_cells = map { |cell| neighbours(*cell, alive: false) }.flatten(1).uniq
filter_cells(empty_cells) { |neighbour_count| neighbour_count == 3 }
end
end
end

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

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

Finished in 0.4268 seconds
18 examples, 0 failures

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

Пламен обнови решението на 15.12.2011 16:51 (преди над 8 години)

+module GameOfLife
+ class Board
+ include Enumerable
+
+ def initialize(*args)
+ @cells = args.uniq
+ end
+
+ def each(&block)
+ @cells.each &block
+ end
+
+ def [](x, y)
+ @cells.include?([x, y])
+ end
+
+ def next_generation
+ Board.new(*(@cells - dead_cells + born_cells))
+ end
+
+ private
+
+ def neighbours(x, y, arg_hash)
+ all_around = ((x - 1)..(x + 1)).to_a.product(((y - 1)..(y + 1)).to_a) - [[x, y]]
+
+ all_around.select { |neighbour| not (arg_hash[:alive] ^ self[*neighbour]) }
+ end
+
+ def filter_cells(cells, &block)
+ cells.select { |cell| yield neighbours(*cell, alive: true).size }
+ end
+
+ def dead_cells
+ filter_cells(@cells) { |neighbour_count| not (2..3).include?(neighbour_count) }
+ end
+
+ def born_cells
+ empty_cells = map { |cell| neighbours(*cell, alive: false) }.flatten(1).uniq
+
+ filter_cells(empty_cells) { |neighbour_count| neighbour_count == 3 }
+ end
+ end
+end