Решение на Шеста задача от Александър Маринов

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

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

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
def initialize(*args)
@live_cells = args.uniq
@live_cells = [] if args == [[]]
@new_gen = []
end
def [] x, y
return true if @live_cells.include? [x, y]
false
end
def each
@live_cells.each do |x, y|
yield x, y
end
end
def count
@live_cells.count
end
def next_generation
@live_cells.each do |cell|
@new_gen << cell if (2..3).include? get_living_neighbours(cell).count
@new_gen |= get_dead_neighbours(cell).select {|c| get_living_neighbours(c).count == 3}
end
Board.new *@new_gen
end
def get_neighbours(cell)
[[cell[0]-1, cell[1]-1], [cell[0]-1, cell[1]], [cell[0]-1, cell[1]+1],
[cell[0], cell[1]-1], [cell[0], cell[1]+1],
[cell[0]+1, cell[1]-1], [cell[0]+1, cell[1]], [cell[0]+1, cell[1]+1]]
end
def get_living_neighbours(cell)
living_neighbours = []
get_neighbours(cell).each do |neighbour_cell|
living_neighbours << neighbour_cell if @live_cells.include? neighbour_cell
end
living_neighbours
end
def get_dead_neighbours(cell)
dead_neighbours = []
get_neighbours(cell).each do |neighbour_cell|
dead_neighbours << neighbour_cell if not @live_cells.include? neighbour_cell
end
dead_neighbours
end
end
end

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

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

Finished in 0.40337 seconds
18 examples, 0 failures

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

Александър обнови решението на 20.12.2011 22:45 (преди над 8 години)

+module GameOfLife
+ class Board
+ include Enumerable
+
+ def initialize(*args)
+ @live_cells = args.uniq
+ @live_cells = [] if args == [[]]
+ @new_gen = []
+ end
+
+ def [] x, y
+ return true if @live_cells.include? [x, y]
+ false
+ end
+
+ def each
+ @live_cells.each do |x, y|
+ yield x, y
+ end
+ end
+
+ def count
+ @live_cells.count
+ end
+
+ def next_generation
+ @live_cells.each do |cell|
+ @new_gen << cell if (2..3).include? get_living_neighbours(cell).count
+ @new_gen |= get_dead_neighbours(cell).select {|c| get_living_neighbours(c).count == 3}
+ end
+ Board.new *@new_gen
+ end
+
+ def get_neighbours(cell)
+ [[cell[0]-1, cell[1]-1], [cell[0]-1, cell[1]], [cell[0]-1, cell[1]+1],
+ [cell[0], cell[1]-1], [cell[0], cell[1]+1],
+ [cell[0]+1, cell[1]-1], [cell[0]+1, cell[1]], [cell[0]+1, cell[1]+1]]
+ end
+
+ def get_living_neighbours(cell)
+ living_neighbours = []
+ get_neighbours(cell).each do |neighbour_cell|
+ living_neighbours << neighbour_cell if @live_cells.include? neighbour_cell
+ end
+ living_neighbours
+ end
+
+ def get_dead_neighbours(cell)
+ dead_neighbours = []
+ get_neighbours(cell).each do |neighbour_cell|
+ dead_neighbours << neighbour_cell if not @live_cells.include? neighbour_cell
+ end
+ dead_neighbours
+ end
+ end
+end