Решение на Шеста задача от Аксения Пенкова

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

Към профила на Аксения Пенкова

Резултати

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

Код

class GameOfLife
class Board
include Enumerable
attr_accessor :live_cells
def initialize(*cells)
@live_cells = cells.uniq
end
def[](x, y)
@live_cells.include?([x, y])? true : false
end
def each(&block)
@live_cells.each { |cell| yield cell }
end
def count
@live_cells.size
end
def to_a
@live_cells
end
def next_generation
survived = @live_cells.select { |x, y| live_neighbours_count(x, y) == 2 or
live_neighbours_count(x, y) == 3 }
reborn = possible_reborn_cells.select { |x, y| live_neighbours_count(x, y) == 3 }
Board.new *(survived + reborn)
end
def neighbours(x, y)
[[x - 1, y + 1], [x, y + 1], [x + 1, y + 1],
[x - 1, y], [x + 1, y],
[x - 1, y - 1], [x , y - 1], [x + 1, y - 1]]
end
def live_neighbours_count(x, y)
neighbours(x, y).map { |x, y| self[x, y] }.select { |element| element == true }.size
end
def possible_reborn_cells
cells = []
@live_cells.each { |x, y| cells += neighbours(x, y) }
cells.uniq - @live_cells
end
end
end

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

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

Finished in 0.39402 seconds
18 examples, 0 failures

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

Аксения обнови решението на 20.12.2011 21:51 (преди над 12 години)

+class GameOfLife
+ class Board
+ include Enumerable
+
+ attr_accessor :live_cells
+
+ def initialize(*cells)
+ @live_cells = cells.uniq
+ end
+
+ def[](x, y)
+ @live_cells.include?([x, y])? true : false
+ end
+
+ def each(&block)
+ @live_cells.each { |cell| yield cell }
+ end
+
+ def count
+ @live_cells.size
+ end
+
+ def to_a
+ @live_cells
+ end
+
+ def next_generation
+ survived = @live_cells.select { |x, y| live_neighbours_count(x, y) == 2 or
+ live_neighbours_count(x, y) == 3 }
+ reborn = possible_reborn_cells.select { |x, y| live_neighbours_count(x, y) == 3 }
+
+ Board.new *(survived + reborn)
+ end
+
+ def neighbours(x, y)
+ [[x - 1, y + 1], [x, y + 1], [x + 1, y + 1],
+ [x - 1, y], [x + 1, y],
+ [x - 1, y - 1], [x , y - 1], [x + 1, y - 1]]
+ end
+
+ def live_neighbours_count(x, y)
+ neighbours(x, y).map { |x, y| self[x, y] }.select { |element| element == true }.size
+ end
+
+ def possible_reborn_cells
+ cells = []
+ @live_cells.each { |x, y| cells += neighbours(x, y) }
+ cells.uniq - @live_cells
+ end
+ end
+end
  • Ако не ти трябва за нещо параметърът block, го махни от дефиницията на функцията, по-бързо ще е: def each(&block)
  • Получаваш count и to_a наготово
  • Подредбата на кода в next_generation май може да се подобри малко

Иначе, като цяло, решението изглежда добре.