Runtime Error in Problem Using Recursion

2

I'm trying to solve the problem 1030 - Flavious Josephus Legend , from a website of challenges.

I send the code and says it has the Runtime error (Accesses an invalid memory or array has little space):

vezes = gets.chomp().to_i
vezes.times do |num|
def jose(n,k) #Fiz o método de maneira correta?
 if (n==0)
    resultado=0  
 else
   return resultado = (( jose(n-1,k)+ k - 1  ) % n)+1 #Eu entendo recursividade, porém acho que fiz errado aqui.
 end
end

phrase=gets.split(" ") #Erro pode estar aqui, não sei fazer de outra maneira que o site aceita a leitura
n=phrase[0].to_i
k=phrase[1].to_i
puts "Case " + (num+1).to_s + ": " + jose(n,k).to_s

end

Is there another way to do the exercise that the site accepts?

    
asked by anonymous 27.08.2018 / 18:57

1 answer

2

I think the problem is that the site expects the answers all together at the end of the program run, not every "enter."

To solve this, a possible solution is to read the data all:

vezes.times do
  my_string += gets
end

And only treat this string after we receive the last input .

Take a look at a slightly altered version of your code:

def jose(n,k)
  if (n==0)
    return 0
  else
    return (( jose(n-1,k)+ k - 1  ) % n)+1
  end
end

vezes = gets.chomp().to_i
my_string = ""

vezes.times do
  my_string += gets
end

phrase=my_string.split(" ")
i = 0

phrase.each_slice(2) do |n, k|
  puts "Case " + (i+=1).to_s + ": " + jose(n.to_i,k.to_i).to_s
end

Edit:

  

Your method is correct - it just probably should not be within a do loop.

    
28.08.2018 / 18:34