Решение на Шеста задача от Николай Добромиров

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

Към профила на Николай Добромиров

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
attr_accessor :cells
def initialize(*args)
@cells = args.uniq
end
def neighbours(x, y)
[[x-1, y-1], [x-1,y], [x-1,y+1], [x,y+1], [x,y-1], [x+1,y+1], [x+1,y-1], [x+1,y]]
end
def [](x, y)
cells.find {|cell_x, cell_y| x == cell_x && y == cell_y} != nil
end
def should_live(x, y)
live_neighbours = neighbours(x, y).select {|x, y| self[x, y]}.count
self[x,y] ? (2..3) === live_neighbours : 3 == live_neighbours
end
def each
cells.each {|x, y| yield x, y}
end
def next_generation
all_cells = cells.map {|x, y| neighbours x, y}.inject(cells, :+).uniq
Board.new *all_cells.select {|x, y| should_live(x, y)}
end
end
end

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

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

Finished in 0.37893 seconds
18 examples, 0 failures

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

Николай обнови решението на 18.12.2011 15:49 (преди над 12 години)

+module GameOfLife
+ class Board
+ include Enumerable
+
+ attr_accessor :cells
+
+ def initialize(*args)
+ @cells = args.uniq
+ end
+
+ def neighbours(x, y)
+ [[x-1, y-1], [x-1,y], [x-1,y+1], [x,y+1], [x,y-1], [x+1,y+1], [x+1,y-1], [x+1,y]]
+ end
+
+ def [](x, y)
+ cells.find {|cell_x, cell_y| x == cell_x && y == cell_y} != nil
+ end
+
+ def should_live(x, y)
+ live_neighbours = neighbours(x, y).select {|x, y| self[x, y]}.count
+ self[x,y] ? (2..3) === live_neighbours : 3 == live_neighbours
+ end
+
+ def each
+ cells.each {|x, y| yield x, y}
+ end
+
+ def next_generation
+ all_cells = cells.map {|x, y| neighbours x, y}.inject(cells, :+).uniq
+ Board.new *all_cells.select {|x, y| should_live(x, y)}
+ end
+ end
+end