Решение на Шеста задача от Деница Генчева

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

Към профила на Деница Генчева

Резултати

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

Код

require 'set'
module GameOfLife
class Board
include Enumerable
attr_reader :alive_cells
def initialize(*alive_cells)
@alive_cells = alive_cells.uniq
end
def each
@alive_cells.each { |cell| yield(cell) }
end
def [](x, y)
@alive_cells.include?([x, y])
end
def count()
alive_cells.count()
end
def next_generation
cells = possible_alive_cells().select{|x, y| alive_in_next_generation?(x, y)}
Board.new(*cells)
end
def alive_in_next_generation?(x, y)
alive_neighbours_count = neighbours(x, y).select {|nx, ny| self[nx, ny] }.count
if (self[x, y])
return alive_neighbours_count == 2 || alive_neighbours_count == 3
end
return alive_neighbours_count == 3
end
def possible_alive_cells()
set = Set.new(alive_cells)
alive_cells.each do |x, y|
set = set + neighbours(x, y)
end
set.to_a
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], [x+1, y+1]]
end
end
end

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

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

Finished in 0.4041 seconds
18 examples, 0 failures

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

Деница обнови решението на 20.12.2011 00:40 (преди над 12 години)

+require 'set'
+
+module GameOfLife
+ class Board
+ include Enumerable
+
+ attr_reader :alive_cells
+
+ def initialize(*alive_cells)
+ @alive_cells = alive_cells.uniq
+ end
+
+ def each
+ @alive_cells.each { |cell| yield(cell) }
+ end
+
+ def [](x, y)
+ @alive_cells.include?([x, y])
+ end
+
+ def count()
+ alive_cells.count()
+ end
+
+ def next_generation
+ cells = possible_alive_cells().select{|x, y| alive_in_next_generation?(x, y)}
+ Board.new(*cells)
+ end
+
+ def alive_in_next_generation?(x, y)
+ alive_neighbours_count = neighbours(x, y).select {|nx, ny| self[nx, ny] }.count
+
+ if (self[x, y])
+ return alive_neighbours_count == 2 || alive_neighbours_count == 3
+ end
+
+ return alive_neighbours_count == 3
+ end
+
+ def possible_alive_cells()
+ set = Set.new(alive_cells)
+ alive_cells.each do |x, y|
+ set = set + neighbours(x, y)
+ end
+ set.to_a
+ 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], [x+1, y+1]]
+ end
+ end
+
+end