向数组添加随机数和非重复数

时间:2015-12-18 20:45:42

标签: c#

如何向数组中添加数字,以使每个新数字是随机且非重复的?

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        const int NUM_ROWS = 5;
        const int NUM_COLS = 7;

        static void Main(string[] args)
        {
            List<List<int>> matrix = new List<List<int>>();
            RandInt randNumbers = new RandInt(NUM_ROWS * NUM_COLS);
            int count = 0;
            for (int row = 0; row < NUM_ROWS; row++)
            {
                List<int> newRow = new List<int>();
                matrix.Add(newRow);
                for (int col = 0; col < NUM_COLS; col++)
                {
                    newRow.Add(RandInt.numbers[count++].number);
                }
            }
        }
        public class RandInt
        {
            public static List<RandInt> numbers = new List<RandInt>();
            public int number { get; set; }
            public int rand { get; set; }

            public RandInt() { }

            public RandInt(int SIZE)
            {
                Random r = new Random();
                for (int i = 0; i < SIZE; i++)
                {
                    numbers.Add(new RandInt() { number = i, rand = r.Next()}); 
                }
                numbers = numbers.OrderBy(x => x.rand).ToList();
            }
        }

    }
}
​

1 个答案:

答案 0 :(得分:0)

您可以使用内置的Random类生成随机数,并使用数组函数Contains检查生成的数字是否已在数组中。在下面的示例中,我生成一个新数字,直到找到一个不在数组中的数字,然后添加它。

Random rand = new Random();
int[] intArray = new int[100];
for (int i = 0; i < 100; i++)
{
    int next = 0;
    while (intArray.Contains(next = rand.Next())) { }
    intArray[i] = next;
}

注意:这种方法的一个缺点是它可能是非终止的,因为它可以无限地生成数组中已经存在的相同数字。但是,对于大多数此类事情的应用,我怀疑这是一个问题。