【问题标题】:Adding Random and Non-Recurring Numbers to an Array [closed]将随机数和非循环数添加到数组[关闭]
【发布时间】:2015-12-18 20:45:42
【问题描述】:

如何将数字添加到数组中,以使每个新数字都是随机且不重复的?

试试这个

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

    }
}
​

【问题讨论】:

  • ...问题是?...
  • 你的意思肯定不是The Matrix
  • 要获得非重复数字,请创建一个 1 到 100 的数组。然后随机化该数组。最简单的方法是创建一个包含两个对象的类 1) int number 2) int randNumber。添加第二个对象的随机数,然后按随机数随机化类。第一个对象编号将随机化。
  • 随机 r = new Random(); int number = rnd.Next(1, 100); // 创建一个介于 1 和 100 之间的数字
  • 帖子的第一行看起来不错。现在请添加您尝试过的内容以及您在实现代码时遇到的问题。您还可以考虑使用您选择的搜索引擎来查找类似的帖子。 IE。 bing.com/search?q=C%23+unique+random+array(到目前为止,帖子中显示的大量研究和努力可能会招来反对票)

标签: c#


【解决方案1】:

您可以使用内置的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;
}

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

【讨论】:

    猜你喜欢
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2016-06-23
    相关资源
    最近更新 更多