Решение на Шеста задача от Иван Арабаджиев

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

Към профила на Иван Арабаджиев

Резултати

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

Код

module GameOfLife
NEIGHBOURS = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]].freeze
WILL_LIVE = [3,12,13].freeze
class Board
include Enumerable
def initialize(*living)
@population = Hash.new(0)
living.each do |cell|
tap_neighbours(*cell) unless cell.length != 2
end
end
def tap_neighbours(cell_x, cell_y)
NEIGHBOURS.each { |other| @population[[cell_x + other[0], cell_y + other[1]]] += 1 }
@population[[cell_x, cell_y]] += 10
end
def each
@population.each_key do |cell|
yield(cell.flatten) unless @population[cell] < 10
end
end
def next_generation
should_live = @population.select do |cell, actual_neighbours|
WILL_LIVE.include? actual_neighbours
end.keys
Board.new *should_live
end
def [](*idx)
@population[[idx[0], idx[1]]] >= 10
end
end
end

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

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

Finished in 0.36657 seconds
18 examples, 0 failures

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

Иван обнови решението на 20.12.2011 21:16 (преди над 12 години)

+module GameOfLife
+ NEIGHBOURS = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]].freeze
+ WILL_LIVE = [3,12,13].freeze
+
+ class Board
+ include Enumerable
+
+ def initialize(*living)
+ @population = Hash.new(0)
+ living.each do |cell|
+ tap_neighbours(*cell) unless cell.length != 2
+ end
+ end
+
+ def tap_neighbours(cell_x, cell_y)
+ NEIGHBOURS.each { |other| @population[[cell_x + other[0], cell_y + other[1]]] += 1 }
+ @population[[cell_x, cell_y]] += 10
+ end
+
+ def each
+ @population.each_key do |cell|
+ yield(cell.flatten) unless @population[cell] < 10
+ end
+ end
+
+ def next_generation
+ should_live = @population.select do |cell, actual_neighbours|
+ WILL_LIVE.include? actual_neighbours
+ end.keys
+ Board.new *should_live
+ end
+
+ def [](*idx)
+ @population[[idx[0], idx[1]]] >= 10
+ end
+ end
+end