Решение на Шеста задача от Виктор Карагяуров

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

Към профила на Виктор Карагяуров

Резултати

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

Код

require 'set'
module GameOfLife
class Board < Enumerator
def initialize *initial_cells
@alive_cells = Set.new initial_cells
@cells = Set.new
@alive_cells.each { |alive_cell| neighbours_of(alive_cell).each { |cell| @cells << cell } }
end
def [] *coords
@alive_cells.include? coords
end
def each
@alive_cells.each { |cell| yield cell }
end
def next_generation
Board.new *(@cells.select { |cell| survives? cell })
end
def survives? cell
neighbours_count = (@alive_cells & neighbours_of(cell)).count
neighbours_count == 3 or (neighbours_count == 2 and @alive_cells.include? cell)
end
def neighbours_of cell
@directions = @directions || ([0, 1, -1].product [0, 1, -1]).reject { |dir| dir.eql? [0, 0] }
@directions.collect { |dir| [cell[0] + dir[0], cell[1] + dir[1]] }
end
end
end

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

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

Finished in 0.3916 seconds
18 examples, 0 failures

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

Виктор обнови решението на 20.12.2011 02:45 (преди над 12 години)

+require 'set'
+
+module GameOfLife
+ class Board < Enumerator
+ def initialize *initial_cells
+ @alive_cells = Set.new initial_cells
+ @cells = Set.new
+ @alive_cells.each { |alive_cell| neighbours_of(alive_cell).each { |cell| @cells << cell } }
+ end
+
+ def [] *coords
+ @alive_cells.include? coords
+ end
+
+ def each
+ @alive_cells.each { |cell| yield cell }
+ end
+
+ def next_generation
+ Board.new *(@cells.select { |cell| survives? cell })
+ end
+
+ def survives? cell
+ neighbours_count = (@alive_cells & neighbours_of(cell)).count
+ neighbours_count == 3 or (neighbours_count == 2 and @alive_cells.include? cell)
+ end
+
+ def neighbours_of cell
+ @directions = @directions || ([0, 1, -1].product [0, 1, -1]).reject { |dir| dir.eql? [0, 0] }
+ @directions.collect { |dir| [cell[0] + dir[0], cell[1] + dir[1]] }
+ end
+ end
+end
  • require директивата няма нужда да е в модула, изведи я в началото на "файла".
  • Напоследък предлагам името neighbours_of, вместо get_neighbours, харесва ми повече.
  • Странно ми е защо ползваш === в evolves?; още, това бих го кръстил survives?.

Това е на първия ред в survives?. Аз питам за втория, където оперираш с два boolean-а:

(neighbours_count == 2) & (@alive_cells.include? cell)

Освен това, скобите са лоша опция тук. Не ги слагай, когато не са нужни. Ако ти трябват, във втория израз, например, ги слагай както си му е редът, около извикването на метода include?: @alive_cells.include?(cell)