【问题标题】:Non-consecutively repeating array of integers非连续重复的整数数组
【发布时间】:2020-03-16 21:42:40
【问题描述】:

我正在尝试生成一个非连续重复的整数数组。到目前为止,我所拥有的效果很好,只是它偶尔会生成一组双 0。我的问题是:

  1. 我怎样才能阻止它
  2. 必须有更好的方法来做到这一点,对吧?太丑了。

感谢您分享任何见解。

这是代码:

        int[] randInts = new int[20];

        Random rand = new Random();


        for (int i = 0; i < 20; i++)
        {
            randInts[i] = rand.Next(0, 8);
        }

        for (int i = 1; i < 20; i++)
        {
            if (randInts[i] == randInts[i - 1] && randInts[i] < 8 && randInts[i] > 0)
            {
                randInts[i]--;
            }

            else if (randInts[i] == randInts[i - 1] && randInts[i] > 0)
            {
                randInts[i]++;
            }
        }

【问题讨论】:

    标签: c# arrays random


    【解决方案1】:
    public IEnumerable<int> NonConsecutiveRepeatingRandomValues(int upperBound)
    {
        Random rand = new Random();
        int prev = -1;
        while(true)
        {
            int value = prev;
            while (value == prev)
                value = rand.Next(upperBound);
            yield return value;
        }
    }
    

    然后为了得到正好 20 个值(而不是永远循环)这样调用它:

    var randInts = NonConsecutiveRepeatingRandomValues(8).Take(20).ToArray();
    

    但仅当您真的需要一个数组时才使用ToArray() 调用。如果没有它,您会感到惊讶。

    【讨论】:

    • 旁注:使用时不要忘记将rand移出静态变量以避免相同的序列...
    • @AlexeiLevenkov 这是 VB.Net 实际上做得更好的少数几件事之一...... VB 有 Shared 而不是 static,但也有一个 Static 关键字可以用来声明方法中的一个变量来获得这种确切的行为(它甚至是线程安全的)。值得庆幸的是,这个问题的方法应该是相当安全的,因为它对整个序列使用相同的实例——但理想情况下,是的,你会保持更长时间。或者,更好的是,使用加密 PRNG。
    • 上限实际上是value = rand.Next(upperBound);中的upperBound - 1。应该记录在案:)
    【解决方案2】:

    当你掷出与上次相同的数字时,你就再掷一次怎么样?

    int[] randInts = new int[20];
    Random rand = new Random();
    
    int lastVal = -1;
    int val = -1;
    
    for (int i = 0; i < 20; i++)
    {   
        while (val == lastVal)
            val = rand.Next(0, 8);  
    
        randInts[i] = val;
        lastVal = val;
    }
    

    当然,您会生成比您需要的更多的随机数,但性能损失不会很大。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 2011-01-22
      • 2011-06-17
      • 1970-01-01
      • 2017-09-14
      相关资源
      最近更新 更多