Решение на Шеста задача от Румен Ангелов

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

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

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
attr_accessor :board
def initialize(*args)
@board = args
end
def each
@board.each { |cell| yield cell[0], cell[1] }
end
def [](x,y)
@board.include? [x, y]
end
def next_generation
args = (@board - die ) | revive
Board.new(*args)
end
private
def revive
array = []
@board.each do |cell|
array<< neighbours(cell).select{ |x| !@board.include? x }.select{ |i| nb_count(i) == 3 }
end
array.flatten(1) | array.flatten(1)
end
def die
@board.select { |cell| nb_count(cell) < 2 or nb_count(cell) > 3 }
end
def neighbours(cell)
[ [cell[0] - 1, cell[1]], [cell[0] + 1, cell[1]], [cell[0], cell[1] - 1], [cell[0], cell[1]+1],
[cell[0] - 1, cell[1] - 1], [cell[0] - 1, cell[1] + 1],
[cell[0] + 1, cell[1] + 1], [cell[0] + 1, cell[1] - 1] ]
end
def nb_count(cell)
cnt = 0
neighbours(cell).each { |i| cnt+=1 if(@board.include? i) }
cnt
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-2e23zh/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.40741 seconds
18 examples, 1 failure

Failed examples:

rspec /tmp/d20111221-3114-2e23zh/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 19:33 (преди над 12 години)

+module GameOfLife
+class Board
+ include Enumerable
+
+ attr_accessor :board
+
+ def initialize(*args)
+ @board = args
+ end
+
+ def each
+ @board.each { |cell| yield cell[0], cell[1] }
+ end
+
+ def [](x,y)
+ @board.include? [x, y]
+ end
+
+ def next_generation
+ args = (@board - die ) | revive
+ Board.new(*args)
+ end
+
+ private
+ def revive
+ array = []
+ @board.each do |cell|
+ array<< neighbours(cell).select{ |x| !@board.include? x }.select{ |i| nb_count(i) == 3 }
+ end
+ array.flatten(1) | array.flatten(1)
+ end
+
+ def die
+ @board.select { |cell| nb_count(cell) < 2 or nb_count(cell) > 3 }
+ end
+
+ def neighbours(cell)
+ [ [cell[0] - 1, cell[1]], [cell[0] + 1, cell[1]], [cell[0], cell[1] - 1], [cell[0], cell[1]+1],
+ [cell[0] - 1, cell[1] - 1], [cell[0] - 1, cell[1] + 1],
+ [cell[0] + 1, cell[1] + 1], [cell[0] + 1, cell[1] - 1] ]
+ end
+
+ def nb_count(cell)
+ cnt = 0
+ neighbours(cell).each { |i| cnt+=1 if(@board.include? i) }
+ cnt
+ end
+end
+end