【问题标题】:Function to generate 2D array with random, non repeating numbers with range of 99生成具有范围为 99 的随机、非重复数字的二维数组的函数
【发布时间】:2015-05-31 14:15:39
【问题描述】:

我需要创建一个函数,该函数生成一个包含 1 - 99 预定义范围的随机非重复数字的二维数组。

static Random RandomGenerator = new Random();

int[][] ran_array ={ 
    new int [10],
    new int [10],
    new int [10] 
};

我正在考虑在一个函数中使用 2 个循环来遍历每个数组,然后在数组中的每个列表中添加数字,所以输出看起来像这样

static Random RandomGenerator = new Random();

int[][] ran_array ={ 
    new int [1, 3, 5, 7, 9, 2, 4, 7, 9, 10],
    new int [23, 24, 12, 53, 75, 87, 20, 12, 25, 11],
    new int [11, 54, 74, 67, 32, 87, 23, 98, 31, 1] 
};

我该怎么做呢?

【问题讨论】:

  • 你的问题不太清楚。您是否尝试过您描述的那种方法?试了有没有遇到什么问题?
  • 数字在二维数组中应该是唯一的还是在它的每一行中都是唯一的?应该将结果数组判断为一个,即int[][] result 还是 2d 一个,即int[,] result

标签: c# arrays random


【解决方案1】:

你可以使用这个方法:

static Random RandomGenerator = new Random();

public static int[][] GetRandomArray(int size1, int size2, int minValue, int maxValue, bool uniqueValues = false) 
{
    int[][] ran_array = new int[size1][];
    for (int i = 0; i < size1; i++)
    {
        ran_array[i] = new int[size2];
        HashSet<int> set = new HashSet<int>();
        for (int ii = 0; ii < size2; ii++)
        {
            int nextValue = RandomGenerator.Next(minValue, maxValue);
            if (uniqueValues)
            {
                while (!set.Add(nextValue))
                    nextValue = RandomGenerator.Next(minValue, maxValue);
            }
            ran_array[i][ii] = nextValue;
        }
    }
    return ran_array;
}

你的样本表明你想要这个:

int[][] ran_array = GetRandomArray(3, 10, 1, 100, true);

【讨论】:

  • 通常随机+不重复+定义的范围点来“创建所有可能值的列表并一个接一个地随机选择(和删除),直到你有足够的(或用完值)”。
【解决方案2】:

在 3 x 10 数组中生成一组随机数字的简单解决方案:

Random rand = new Random();
var availableNumbers = Enumerable.Range(1, 99).ToList();
var result = new int[3,10];

for(int i = 0; i < 3; i++){
    for(var j = 0; j < 10; j++)
    {
        result[i,j] = availableNumbers
                       .Skip(rand.Next(0, availableNumbers.Count()))
                       .First();

        // Remove used numbers to avoid duplicates:
        availableNumbers.Remove(result[i,j]);
    }
}

也许不是最有效的解决方案,但它很有效,而且相当简单。

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多