Решение на Шеста задача от Евгени Кунев

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

Към профила на Евгени Кунев

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
def initialize(*living_cells)
@alive = living_cells
end
def each
@alive.each { |cell| yield cell }
end
def [](x, y)
@alive.include? [x,y]
end
def next_generation
next_living = remain_alive + newborn
Board.new *next_living.uniq
end
def remain_alive
@alive.select do |cell|
neighbours = living_neighbours_count(cell)
2 <= neighbours and neighbours <= 3
end
end
def newborn
@alive.inject([]) { |potential, cell| potential + Board.neighbours(cell) }
.select { |cell| living_neighbours_count(cell) == 3}
end
def living_neighbours_count(cell)
Board.neighbours(cell).select { |cell| self[*cell] }.count
end
def self.neighbours(cell)
x, y = cell
[x - 1, x, x + 1].product([y - 1, y, y + 1]).reject { |cell| cell == [x, y] }
end
end
end

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

......F...........

Failures:

  1) GameOfLife::Board GameOfLife::Board enumeration live cells count returns the number of live cells on a board
     Failure/Error: new_board([0, 0], [1, 1], [0, 0]).count.should eq 2
       
       expected: 2
            got: 3
       
       (compared using ==)
     # /tmp/d20111221-3114-1a9ckyi/spec.rb:46:in `block (4 levels) in <top (required)>'
     # ./lib/homework/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/homework/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.44989 seconds
18 examples, 1 failure

Failed examples:

rspec /tmp/d20111221-3114-1a9ckyi/spec.rb:43 # GameOfLife::Board GameOfLife::Board enumeration live cells count returns the number of live cells on a board

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

Евгени обнови решението на 16.12.2011 01:31 (преди над 8 години)

+module GameOfLife
+ class Board
+ include Enumerable
+ def initialize(*living_cells)
+ @alive = living_cells
+ end
+
+ def each
+ @alive.each { |cell| yield cell }
+ end
+
+ def [](x, y)
+ @alive.include? [x,y]
+ end
+
+ def next_generation
+ next_living = remain_alive + newborn
+ Board.new *next_living.uniq
+ end
+
+ def remain_alive
+ @alive.select do |cell|
+ neighbours = living_neighbours_count(cell)
+ 2 <= neighbours and neighbours <= 3
+ end
+ end
+
+ def newborn
+ @alive.inject([]) { |potential, cell| potential + Board.neighbours(cell) }
+ .select { |cell| living_neighbours_count(cell) == 3}
+ end
+
+ def living_neighbours_count(cell)
+ Board.neighbours(cell).select { |cell| self[*cell] }.count
+ end
+
+ def self.neighbours(cell)
+ x, y = cell
+ [x - 1, x, x + 1].product([y - 1, y, y + 1]).reject { |cell| cell == [x, y] }
+ end
+ end
+end