【问题标题】:generate random numbers with no repeat in c#在c#中生成不重复的随机数
【发布时间】:2012-05-27 08:39:44
【问题描述】:

如何在 C# 中生成不重复的随机数。我有一个数组,我想用 0 到 9 的随机数填充每个房间。每个房间应该有不同的数字。我用这个:

for (int i = 0; i < 20; i++)
{
    Random rnd = new Random();
    int temp = 0;
    temp = rnd.Next(0, 9);
    page[i] = temp;
}

但我在每个房间的数组中得到相同的数字。

【问题讨论】:

  • "我只想知道如何在 c# 中生成不重复的随机数?" - 这不可能。假设一个随机数重复,否则它实际上不是一个随机数生成器,而是一个唯一值生成器,它很容易编码。您的代码也存在缺陷,因为您将始终拥有相同的种子值。
  • 你说的是房间但有一个页面数组!?您的意思是数组页面中的每个条目都应该是唯一的吗?我理解你是否正确,你希望页面中有 20 位数字,所有数字都是不同的?

标签: c# random numbers


【解决方案1】:

有了这么小的数字列表可供选择,您只需生成一个包含所有数字的列表,然后shuffle它们。

【讨论】:

    【解决方案2】:

    您的问题是您在每个循环中都创建了 Random 对象。 Random 对象只能创建一次。试试这个:

    Random rnd = new Random(); // <-- This line goes out of the loop        
    for (int i = 0; i < 20; i++) {
        int temp = 0;
        temp = rnd.Next(0, 9);
        page[i] = temp;
    }
    

    【讨论】:

      【解决方案3】:

      这将创建一个从 1 到 rangeEx 的唯一范围。接下来的两行创建一个随机数生成器,并使用随机数对 IEnumerable 范围进行排序。然后用 ToArray 调用 this 并返回!

         private int[] RandomNumber(int rangeEx)
          {
              var orderedList = Enumerable.Range(1, range);
              var rng = new Random();
              return orderedList.OrderBy(c => rng.Next()).ToArray();
          }
      

      【讨论】:

        【解决方案4】:
                ArrayList page=new ArrayList();
                int random_index;            
                random rnd = new Random();
        
                for (int i = 0; i < 20; i++)
                {
                    do                            
                    {
                        random_index = rnd.Next(10);
                        if (!(page.Contains(random_index)))
                                        break;
                    } while (page.Contains(random_index));
                    page.Add(random_index);
                }
        

        【讨论】:

        • 你能解释一下你的答案吗?
        【解决方案5】:
            public Form1()
            {
                InitializeComponent();
            }
            int A, B;
            string Output;
            private void Form1_Load(object sender, EventArgs e)
            {
                for (int i = 0; i < 20; i++)
                {
                    while (A == B)
                    {
                        Random r = new Random();
                        A = r.Next(1, 6);
                    }
                    Output = Output + A;
                    B = A;
                }
                textBox1.Text = Output;
            }
        

        输出:24354132435213245415(不重复)

        【讨论】:

          【解决方案6】:
          using System;
          
          using System.Collections.Generic;
          
          using System.Linq;
          
          
          namespace nonRepeatableRndm
          {
          
              class Program
              {
                  //variable with the Values
                  List<string> RandomVal = new List<string>();
                  //variable to compare the randomly genarated Values
                  List<string> CompaerbyString = new List<string>();
                  //Variable that gets Value from  the list Values
                  string DisplayVal;
                  //instantiates the Random Class
                  Random r;
                  //this Method gives Value to the list and initializes th the Random Class
                  void setVal()
                  {
                      //Adding to the list
                      RandomVal.Add("A");
                      RandomVal.Add("b");
                      RandomVal.Add("c");
                      RandomVal.Add("d");
                      RandomVal.Add("e");
                      RandomVal.Add("f");
                      RandomVal.Add("g");
                      RandomVal.Add("h");
                      RandomVal.Add("i");
                      RandomVal.Add("j");
                      RandomVal.Add("k");
                      RandomVal.Add("l");
                      RandomVal.Add("m");
                      RandomVal.Add("n");
                      RandomVal.Add("o");
                      RandomVal.Add("p");
                      RandomVal.Add("q");
                      RandomVal.Add("r");
                      RandomVal.Add("s");
                      RandomVal.Add("t");
                      RandomVal.Add("u");
                      RandomVal.Add("v");
                      RandomVal.Add("w");
                      RandomVal.Add("x");
                      RandomVal.Add("y");
                      RandomVal.Add("z");
          
                      //Instantiating the Random Method
                      r = new Random();
                  }
                  //This method Gives Out the Random Values
                  public void DisplayRand()
                  {
          
                     //Setting Random Index 
                     int getIndex =  r.Next(0, RandomVal.Count - 1);
                      //Now we are trying to pass a random value to the String 
                      DisplayVal = RandomVal.ElementAt<string>(getIndex);
                      //we are testing to see if String in Display is contained in the List that will used Compare
                      if (!CompaerbyString.Contains(DisplayVal))
                          Console.WriteLine(DisplayVal.ToUpper());
                      else
                      {
                          try
                          {
                              this.DisplayRand();
                          }
                          catch(Exception e)
                          {
                              Console.WriteLine("You have Reached the End of the list...");
                              Environment.Exit(0);
                          }
                      }
                      //Adding Corrent DisplayVal's Value to the List for Comparison
                      CompaerbyString.Add(DisplayVal);
                  }
                  //This is Simple method that Calls the Display
                  void Call()
                  {
                      //This For loop is to Ensure we have no Stack Overflow
                      for ( int i = 0; i < RandomVal.Count-1;i++)
                      {
                          this.DisplayRand();
          
                      }
                  }
                  static void Main(string[] args)
                  {
                      Console.WriteLine("Random Values With Out Repeatating Any Value");
                      //Simple Instantiation
                      Program dis = new Program();
                      //Simple Call
                      dis.setVal();
                      //Simple Call
                      dis.Call() ;
                      Console.ReadLine();   
                  }
              }
          }
          

          【讨论】:

            【解决方案7】:

            100% 正确

               public int[] UniqeRandomArray(int size , int Min , int Max ) {
            
                    int [] UniqueArray = new int[size];
                    Random rnd = new Random();
                    int Random;
            
                    for (int i = 0 ; i < size ; i++) {
            
                        Random = rnd.Next(Min, Max);
            
                        for (int j = i; j >= 0 ; j--) {
            
                            if (UniqueArray[j] == Random)
                            { Random = rnd.Next(Min, Max); j = i; }
            
                        }
            
                        UniqueArray[i] = Random;
            
                    }
            
                    return UniqueArray;
            
                }
            

            // 注意是唯一的 [Max - Min > size] 不等于

            【讨论】:

            • 另外,这对于大型数组来说根本不是有效的,而是您可以创建一个排序数组并使用一种改组技术来创建随机性
            猜你喜欢
            • 1970-01-01
            • 2016-08-20
            • 2015-07-12
            • 2012-12-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多