Решение на Шеста задача от Борис Минев

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

Към профила на Борис Минев

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
attr_accessor :cells, :neighbours, :dead_cells
def initialize *cells
@cells = cells.uniq
@neighbours = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
@dead_cells = dead_neighbours
end
def next_generation
cells_new = @cells.dup
cells_new = apply_rules cells_new
Board.new *cells_new
end
def apply_rules cells_new
remained = @cells.select { |x, y| alive? x, y }
new = @dead_cells.select { |x, y| alive_count(x, y) == 3 }
remained + new
end
def alive? x, y
alive_count(x, y) == 2 || alive_count(x, y) == 3
end
def alive_count x, y
@neighbours.count { |i, j| @cells.include? [x+i, y+j] }
end
def dead_neighbours
dead = []
@cells.each do |x, y|
dead |= @neighbours.map { |i, j| [x+i, y+j] }
end
dead
end
def each(&block)
@cells.each(&block)
end
def [] (x, y)
@cells.include?([x, y]) ? true : false
end
def to_a
@cells
end
def count
@cells.count
end
end
end

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

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

Finished in 0.40428 seconds
18 examples, 0 failures

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

Борис обнови решението на 20.12.2011 04:04 (преди над 8 години)

+module GameOfLife
+ class Board
+ include Enumerable
+ attr_accessor :cells, :neighbours, :dead_cells
+
+ def initialize *cells
+ @cells = cells.uniq
+ @neighbours = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
+ @dead_cells = dead_neighbours
+ end
+
+ def next_generation
+ cells_new = @cells.dup
+ cells_new = apply_rules cells_new
+ Board.new *cells_new
+ end
+
+ def apply_rules cells_new
+ remained = @cells.select { |x, y| alive? x, y }
+ new = @dead_cells.select { |x, y| alive_count(x, y) == 3 }
+ remained + new
+ end
+
+ def alive? x, y
+ alive_count(x, y) == 2 || alive_count(x, y) == 3
+ end
+
+ def alive_count x, y
+ @neighbours.count { |i, j| @cells.include? [x+i, y+j] }
+ end
+
+ def dead_neighbours
+ dead = []
+ @cells.each do |x, y|
+ dead |= @neighbours.map { |i, j| [x+i, y+j] }
+ end
+ dead
+ end
+
+ def each(&block)
+ @cells.each(&block)
+ end
+
+ def [] (x, y)
+ @cells.include?([x, y]) ? true : false
+ end
+
+ def to_a
+ @cells
+ end
+
+ def count
+ @cells.count
+ end
+ end
+end