Runtime Error in Problem Using Recursion

Asked

Viewed 99 times

2

I’m trying to solve the problem 1030 - Flavious Josephus Legend, from a challenge site.

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

There is another way to do the exercise that the site accepts?

1 answer

2


I believe the problem is that the site expects the answers all together at the end of the program execution, and not each "enter".

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

vezes.times do
  my_string += gets
end

And just treat that 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

resultado de envio da solução


Edit:

Your method is correct - it just probably shouldn’t be inside a loop do.

  • I made a comment up there on my code and also what does each_slice(2) mean? I know what "each" is, but not "Slice"...

  • @Misaee21 saw her edition - as for her, two things: wrong is a strong word - no, it’s not wrong, but is it necessary? : ) and avoid editing questions already answered to include new questions; there is not exactly a "follow up" of questions on Sopt, except when creating a new one - to clarify this and other simpler questions, I suggest you visit the chat.

  • @Misaee21 the each.slice(n) return to you n elements rather than just one, as in the case of each.

  • 1

    https://i.etsystatic.com/12780725/d/il/3f8d4e/1369912852/il_340x270.1369912852_teyg.jpg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.