vendredi 28 août 2020

C# : Stack Overflow Exception during recursive method

I have a recursive method that calls itself whenever the random generated number isn't equal to 1. I'm trying to test odds on different things such as a shiny pokemon (1/8192) or a 12-eyes seed in Minecraft (10^12), even though I understand why the Stack Overflow is happening, I don't know how to fix it. Using Threads slows it down by a lot (5000 calculations/s without, around 500 with threading).

Here's the code:

static void shiny()
{
    total = 0;
    counter += 1;
    resetcounter += 1;
    if (rdm.Next(8192) + 1 == 1)
    {
        Console.WriteLine("SHINY !! In: " + counter + " resets.");
    }
    else
    {
        if (resetcounter > 7000)
        {
            Console.WriteLine("Reset. Current: " + counter);
            ThreadStart newtask = new ThreadStart(shiny);
            Thread task = new Thread(newtask);
            task.Start();
        }
        else
        {
            Console.WriteLine("Reset. Current: " + counter);
            shiny();
        }
    }
}

I use the resetcounter variable to avoid the Stack Overflow error since it's happening around 7k "resets", then it starts a new thread. I'd love to understand how testing odds can avoid stack overflow though !




Aucun commentaire:

Enregistrer un commentaire