Stack level too deep in Ruby trying to draw a random card

妖精的绣舞 提交于 2019-12-02 05:38:44

I think it's safe to say the recursion is causing the error. Seems to me you don't need recursion, you could just loop until you get drawn_card != 0, e.g.,

drawn_card = 0
while drawn_card == 0
  choice_of_card = rand($deck.length); #choose a random card out of the deck
  drawn_card = $deck[choice_of_card]; #draw that random card from the deck
end

As written, the recursion depth is "unlimited" based on the random number generator. Consider when there is only one card left in the deck. It will keep choosing random numbers and recursing until it finally picks the one card left; a very deep stack potentially. With one card remaining in a 52 card deck, the odds of not selecting the remaining card any one time is 51/52=98%. To get to a 50% chance of selecting it, you need about 35 iterations/recursions. To reach a 99% chance of selecting it, it needs about 237 iterations: (1.0 - (51/52)^237)=99%.

To use this particular implementation, it would be necessary to change it to a loop (just iterate rather than recurse). However, that is still not very efficient and could loop a long time before finding one of the few remaining cards. An alternative might be to remove the gaps from the deck as cards are removed and then there will always be a hit. Or maybe use a shuffling algorithm up front and then just iterate through them sequentially.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!