how to avoid number repeation by using random clas

2019-01-27 06:28发布

问题:

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.

回答1:

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


回答2:

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.