Решение на Шеста задача от Елена Иванова

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

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

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
attr_accessor :board
def initialize(*args)
@board = args.uniq
end
def next_generation
new_board = @board.select { |cell| [2, 3].include? live_neighbours_count(cell) }
@board.each do |cell|
new_board += dead_neighbours(cell).select { |cell| live_neighbours_count(cell) == 3 }
end
Board.new *new_board.uniq
end
def [] cell_x, cell_y
@board.include? [cell_x, cell_y]
end
def each
@board.each { |cell| yield cell }
end
private
def live_neighbours_count cell
neighbours(cell).select { |cell| @board.include? cell }.count
end
def dead_neighbours cell
n = neighbours(cell).reject { |cell| @board.include? cell }
end
def neighbours cell
x, y = cell
([x, x - 1, x + 1].product [y, y - 1, y + 1]) - [[x, y]]
end
end
end

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

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

Finished in 0.43339 seconds
18 examples, 0 failures

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

Елена обнови решението на 17.12.2011 11:19 (преди над 8 години)

+module GameOfLife
+
+ class Board
+
+ include Enumerable
+
+ attr_accessor :board
+
+ def initialize(*args)
+ @board = args.uniq
+ end
+
+ def next_generation
+ new_board = @board.select { |cell| [2, 3].include? live_neighbours_count(cell) }
+ @board.each do |cell|
+ new_board += dead_neighbours(cell).select { |cell| live_neighbours_count(cell) == 3 }
+ end
+ Board.new *new_board.uniq
+ end
+
+ def [] cell_x, cell_y
+ @board.include? [cell_x, cell_y]
+ end
+
+ def each
+ @board.each { |cell| yield cell }
+ end
+
+ private
+
+ def live_neighbours_count cell
+ neighbours(cell).select { |cell| @board.include? cell }.count
+ end
+
+ def dead_neighbours cell
+ n = neighbours(cell).reject { |cell| @board.include? cell }
+ end
+
+ def neighbours cell
+ x, y = cell
+ ([x, x - 1, x + 1].product [y, y - 1, y + 1]) - [[x, y]]
+ end
+ end
+
+end