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

陌路散爱 提交于 2019-11-29 12:30:14

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!