如何减少stackOverFlow C# [英] How to reduce stackOverFlow C#

查看:129
本文介绍了如何减少stackOverFlow C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法生成一个可能是2x2到7x7的随机数组,但是为了有效它应该满足一定的条件。

这就是为什么我依赖于内部的递归导致StackOverFlow的方法,因为有时需要超过6700尝试没有结果,程序崩溃。

无论如何还有减少这个机会吗?



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?

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;
       }

推荐答案

为什么要递归?循环就足够了。



Why recursion? A Loop is enough.

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;
       }


这篇关于如何减少stackOverFlow C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆