Решение на Шеста задача от Георги Христозов

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

Към профила на Георги Христозов

Резултати

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

Код

module GameOfLife
class Generator
def self.next_generation(board)
Board.new(*board.select{ |x,y| board.live_neighbours_count(x,y).between?(2,3)} +
board.map{ |x,y| board.dead_neighbours(x,y)}.inject([],&:|).
select{|x,y| board.live_neighbours_count(x,y) == 3})
end
end
class Board
include Enumerable
def initialize(*initial_values)
@cells = initial_values.uniq
end
def [](x,y)
return @cells.index([x,y]) != nil
end
def each
@cells.each do |pair|
yield pair
end
end
def get_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)
get_neighbours(x,y).select{|x1,y1| self[x1,y1]}.length
end
def dead_neighbours(x,y)
get_neighbours(x,y).select{|x1,y1| not self[x1,y1]}
end
def next_generation
Generator.next_generation(self)
end
end
end

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

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

Finished in 0.59516 seconds
18 examples, 0 failures

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

Георги обнови решението на 15.12.2011 17:15 (преди над 8 години)

+module GameOfLife
+ class Generator
+ def self.next_generation(board)
+ Board.new(*board.select{ |x,y| board.live_neighbours_count(x,y).between?(2,3)} +
+ board.map{ |x,y| board.dead_neighbours(x,y)}.inject([],&:|).
+ select{|x,y| board.live_neighbours_count(x,y) == 3})
+ end
+ end
+
+ class Board
+ include Enumerable
+
+ def initialize(*initial_values)
+ @cells = initial_values.uniq
+ end
+
+ def [](x,y)
+ return @cells.index([x,y]) != nil
+ end
+
+ def each
+ @cells.each do |pair|
+ yield pair
+ end
+ end
+
+ def get_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)
+ get_neighbours(x,y).select{|x1,y1| self[x1,y1]}.length
+ end
+
+ def dead_neighbours(x,y)
+ get_neighbours(x,y).select{|x1,y1| not self[x1,y1]}
+ end
+
+ def next_generation
+ Generator.next_generation(self)
+ end
+ end
+end