Решение на Шеста задача от Емилиян Янков

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

Към профила на Емилиян Янков

Резултати

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

Код

module GameOfLife
class Board
include Enumerable
def initialize (*args)
@board = Hash.new(0)
args.each do |elem|
@board[elem] = 1
end
end
def [] (a,b)
if @board[Array[a,b]] == 1
true
else
false
end
end
def each
@board.each_key {|x| yield x}
end
def add_cell(elem)
@board[elem] = 1
end
def next_generation (temp_board = Board.new)
@board.each_key do |x,y|
temp_board = rule1(x,y,temp_board)
temp_board = rule4(x,y,temp_board)
end
return temp_board
end
def count_cell (a,b,temp_arr = [[-1,-1],[-1,0],[0,-1],[1,1],[1,0],[0,1],[-1,1],[1,-1]])
temp_arr.map{|x,y| @board[Array[x+a,y+b]]}.inject(:+)
end
def rule1(a,b,temp_board)
if count_cell(a,b) == 2 or count_cell(a,b) == 3
temp_board.add_cell(Array[a,b])
end
return temp_board
end
def rule4(a,b,temp_board,temp_arr = [[-1,-1],[-1,0],[0,-1],[1,1],[1,0],[0,1],[-1,1],[1,-1]])
temp_arr.each do |x,y|
if count_cell(x+a,y+b) == 3
temp_board.add_cell(Array[a+x,b+y])
end
end
return temp_board
end
end
end

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

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

Finished in 0.39986 seconds
18 examples, 0 failures

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

Емилиян обнови решението на 19.12.2011 23:41 (преди около 13 години)

+module GameOfLife
+
+class Board
+include Enumerable
+
+ def initialize (*args)
+ @board = Hash.new(0)
+ args.each do |elem|
+ @board[elem] = 1
+ end
+ end
+
+ def [] (a,b)
+ if @board[Array[a,b]] == 1
+ true
+ else
+ false
+ end
+ end
+
+ def each
+ @board.each_key {|x| yield x}
+ end
+
+ def add_cell(elem)
+ @board[elem] = 1
+ end
+
+ def next_generation (temp_board = Board.new)
+ @board.each_key do |x,y|
+ temp_board = rule1(x,y,temp_board)
+ temp_board = rule4(x,y,temp_board)
+ end
+ return temp_board
+ end
+
+
+ def count_cell (a,b,temp_arr = [[-1,-1],[-1,0],[0,-1],[1,1],[1,0],[0,1],[-1,1],[1,-1]])
+ temp_arr.map{|x,y| @board[Array[x+a,y+b]]}.inject(:+)
+ end
+
+ def rule1(a,b,temp_board)
+ if count_cell(a,b) == 2 or count_cell(a,b) == 3
+ temp_board.add_cell(Array[a,b])
+ end
+ return temp_board
+ end
+
+
+ def rule4(a,b,temp_board,temp_arr = [[-1,-1],[-1,0],[0,-1],[1,1],[1,0],[0,1],[-1,1],[1,-1]])
+ temp_arr.each do |x,y|
+ if count_cell(x+a,y+b) == 3
+ temp_board.add_cell(Array[a+x,b+y])
+ end
+ end
+ return temp_board
+ end
+
+ end
+
+end
+