how to avoid number repeation by using random class in c#?

后端 未结 2 787
灰色年华
灰色年华 2020-12-20 07:10

hi i am using Random class for getting random numbers but my requirement is once it generate one no that should not be repeate again pls help me.

相关标签:
2条回答
  • 2020-12-20 07:45

    The following C# code shows how to obtain 7 random cards with no duplicates. It is the most efficient method to use when your random number range is between 1 and 64 and are integers:

    ulong Card, SevenCardHand;
    int CardLoop;
    const int CardsInDeck = 52;
    
    Random RandObj = new Random(Seed);
    
    for (CardLoop = 0; CardLoop < 7; CardLoop++)
    {
      do
      {
        Card = (1UL << RandObj.Next(CardsInDeck));
      } while ((SevenCardHand & Card) != 0);
      SevenCardHand |= Card;
    }
    

    If the random number range is greater than 64, then the next most efficient way to get random numbers without any duplicates is as follows from this C# code:

    const int MaxNums = 1000;
    int[] OutBuf = new int[MaxNums];
    int MaxInt = 250000;  // Reps the largest random number that should be returned.
    int Loop, Val;
    // Init the OutBuf with random numbers between 1 and MaxInt, which is 250,000.
    BitArray BA = new BitArray(MaxInt + 1);
    for (Loop = 0; Loop < MaxNums; Loop++)
    {
       // Avoid duplicate numbers.
       for (; ; )
       {
         Val = RandObj.Next(MaxInt + 1);
         if (BA.Get(Val))
           continue;
         OutBuf[Loop] = Val;
         BA.Set(Val, true);
         break;
       }
    }
    

    The drawback with this technique is that it tends to use more memory, but it should be significantly faster than other approaches since it does not have to look through a large container each time a random number is obtained.

    0 讨论(0)
  • 2020-12-20 08:01

    Keep a list of the generated numbers and check this list before returning the next random.

    Since you have not specified a language, I'll use C#

    List<int> generated = new List<int>;
    public int Next()
    {
       int r;
       do {  r = Random.Next() } while generated.Contains(r);
       generated.Add(r);
       return r;
    }
    
    0 讨论(0)
提交回复
热议问题