Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have the following method to generate a random array that might be 2x2 up to 7x7, but in order to be valid it should meet a certain condition.
That's why I relied on recursion inside the method which causes StackOverFlow because sometimes it take more than 6700 tried with no results and the program crashes.
Is there anyway to reduce that chance?

C#
public double [,] GenerateKey(int dimension)
       {
           recCounter++;
           bool valid;
           Random rand = new Random();
           double[,] key = new double[dimension, dimension];
           for (int i = 0; i < key.GetLength(0); i++)
           {
               for (int j = 0; j < key.GetLength(1); j++)
               {
                   key[i, j] = rand.Next(-26, 27);
               }
           }
           valid = checkKey(key);
           if (!valid)
           {
              key= GenerateKey(dimension);
           }
           else
           {
               MessageBox.Show("Valid Key! :)");
               return key;
           }
           return key;
       }
Posted
Comments
[no name] 12-Oct-14 6:17am    
And why you Need to solve that with recursion?

1 solution

Why recursion? A Loop is enough.

C#
public double [,] GenerateKey(int dimension)
       {
           bool valid;
           Random rand = new Random();
           double[,] key = new double[dimension, dimension];

           while(true)
           {
              recCounter++;
              for (int i = 0; i < key.GetLength(0); i++)
              {
                  for (int j = 0; j < key.GetLength(1); j++)
                  {
                      key[i, j] = rand.Next(-26, 27);
                  }
              }
              valid = checkKey(key);
              if (valid)
              {
                  MessageBox.Show("Valid Key! :)");
                  break;
              }
           }
           return key;
       }
 
Share this answer
 
Comments
Wael Tayara 12-Oct-14 12:52pm    
Thank you, you are totally right about that. No need for recursion at all ...
[no name] 12-Oct-14 12:56pm    
Thank you. Regards, Bruno

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900