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

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

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

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
def initialize(*args)
@cells = Hash.new(false)
args.each { |item| @cells[item] = true }
end
def next_generation
new_cells = get_new_cells
get_dead_cells.each { |cell| new_cells[cell] = true if live_neighbours_count(cell) == 3 }
return Board.new(*new_cells.delete_if { |cell, alive| !alive }.keys)
end
def each &block
@cells.each { |coords, is_alive| yield coords }
end
def [](x, y)
@cells.include? [x, y]
end
private
def get_new_cells
new_cells = Hash.new(false)
@cells.each { |cell, alive| new_cells[cell] = (2..3).include?(live_neighbours_count(cell)) }
return new_cells
end
def get_dead_cells
dead_cells = []
@cells.each { |cell, alive| dead_cells += cell_neighbours(cell) }
dead_cells.delete_if { |cell| @cells[cell] }.uniq!
return dead_cells
end
def cell_neighbours cell
x, y = cell[0], cell[1]
neighbours = [x+1,y], [x+1,y+1], [x+1,y-1], [x,y+1], [x,y-1], [x-1,y+1], [x-1,y-1], [x-1,y]
return neighbours
end
def live_neighbours_count cell
neighbours = cell_neighbours(cell)
return neighbours.count { |neighbour| @cells[neighbour] }
end
end
end

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

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

Finished in 0.37456 seconds
18 examples, 0 failures

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

Борис обнови решението на 20.12.2011 01:05 (преди около 13 години)

+module GameOfLife
+ class Board
+ include Enumerable
+
+ def initialize(*args)
+ @cells = Hash.new(false)
+ args.each { |item| @cells[item] = true }
+ end
+
+ def next_generation
+ new_cells = get_new_cells
+ get_dead_cells.each { |cell| new_cells[cell] = true if live_neighbours_count(cell) == 3 }
+ return Board.new(*new_cells.delete_if { |cell, alive| !alive }.keys)
+ end
+
+ def each &block
+ @cells.each { |coords, is_alive| yield coords }
+ end
+
+ def [](x, y)
+ @cells.include? [x, y]
+ end
+
+ private
+
+ def get_new_cells
+ new_cells = Hash.new(false)
+ @cells.each { |cell, alive| new_cells[cell] = (2..3).include?(live_neighbours_count(cell)) }
+ return new_cells
+ end
+
+ def get_dead_cells
+ dead_cells = []
+ @cells.each { |cell, alive| dead_cells += cell_neighbours(cell) }
+ dead_cells.delete_if { |cell| @cells[cell] }.uniq!
+ return dead_cells
+ end
+
+ def cell_neighbours cell
+ x, y = cell[0], cell[1]
+ neighbours = [x+1,y], [x+1,y+1], [x+1,y-1], [x,y+1], [x,y-1], [x-1,y+1], [x-1,y-1], [x-1,y]
+ return neighbours
+ end
+
+ def live_neighbours_count cell
+ neighbours = cell_neighbours(cell)
+ return neighbours.count { |neighbour| @cells[neighbour] }
+ end
+ end
+end