Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Random 如何在c#中使用随机类避免数字重复?_Random_Numbers - Fatal编程技术网

Random 如何在c#中使用随机类避免数字重复?

Random 如何在c#中使用随机类避免数字重复?,random,numbers,Random,Numbers,您好,我使用随机类获取随机数,但我的要求是,一旦生成一个不应再次重复的“否”,请帮助我。保留生成的数字列表,并在返回下一个随机数之前检查此列表 因为您没有指定语言,所以我将使用C# 生成的列表=新列表; 公共int Next() { INTR; 生成.Contains(r)时do{r=Random.Next()}; 生成。添加(r); 返回r; } 以下C#代码显示了如何获得7张无重复的随机卡。当您的随机数范围介于1和64之间且为整数时,这是最有效的方法: ulong Card, SevenCa

您好,我使用随机类获取随机数,但我的要求是,一旦生成一个不应再次重复的“否”,请帮助我。

保留生成的数字列表,并在返回下一个随机数之前检查此列表

因为您没有指定语言,所以我将使用C#

生成的列表=新列表;
公共int Next()
{
INTR;
生成.Contains(r)时do{r=Random.Next()};
生成。添加(r);
返回r;
}
以下C#代码显示了如何获得7张无重复的随机卡。当您的随机数范围介于1和64之间且为整数时,这是最有效的方法:

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;
}
ulong卡,七分钱;
int-CardLoop;
常数int CardsInDeck=52;
Random RandObj=新随机(种子);
用于(CardLoop=0;CardLoop<7;CardLoop++)
{
做
{

Card=(1UL如果这是你的要求,为什么你首先使用Random?是的,这是我能想到的唯一确定的方法,+1
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;
}
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;
   }
}