SoFunction
Updated on 2025-03-06

C# generates non-repetitive random numbers within the specified range

C# generates non-repetitive random numbers within the specified range

// Number random number// minNum random number lower limit// maxNum random number upper limitpublic int[] GetRandomArray(int Number,int minNum,int maxNum)
 {
  int j;
  int[] b=new int[Number];
  Random r=new Random();
  for(j=0;j<Number;j++)
  {
  int i=(minNum,maxNum+1);
  int num=0;
  for(int k=0;k<j;k++)
  {
   if(b[k]==i)
   {
   num=num+1;
   }
  }
  if(num==0 )
  {
   b[j]=i;
  }
  else
  {
   j=j-1;
  }
  }
  return b;
 }

Let’s introduce the implementation methods of other netizens:

Method 1: The idea is to use an array to save the index number, first randomly generate an array position, then take out the index number of the randomly drawn position, and copy the last index number to the current array position, and then subtract the upper limit of the random number by one. For example, first place these 100 numbers in an array, and take a random position at a time (the first time is 1-100, the second time is 1-99,...), and replace the number at that position with the last number.

int[] index = new int[15]; 
for (int i = 0; i < 15; i++) 
index = i; 
Random r = new Random(); 
// Used to save randomly generated 10 unrepetitive numbersint[] result = new int[10]; 
int site = 15;//Set the upper limitint id; 
for (int j = 0; j < 10; j++) 
{ 
id = (1, site - 1); 
//Fetch a number at a random position and save it to the result arrayresult[j] = index[id]; 
//Copy the last number to the current locationindex[id] = index[site - 1]; 
//The upper limit of the position is reduced by onesite--; 
}

Method 2: Utilize Hashtable.

Hashtable hashtable = new Hashtable(); 
Random rm = new Random(); 
int RmNum = 10; 
for (int i = 0;  < RmNum; i++) 
{ 
  int nValue = (100); 
if (!(nValue) && nValue != 0) 
{ 
  (nValue, nValue); 
  (()); 
} 
}

Method 3: Recursively, use it to detect whether the generated random number is repeated. If the retrieved number and the obtained number are repeated, it will be retrieved again randomly.

Random ra=new Random(unchecked((int))); 
int[] arrNum=new int[10]; 
int tmp=0; 
int minValue=1; 
int maxValue=10; 
for (int i=0;i&lt;10;i++) 
{ 
tmp=(minValue,maxValue); //Number of random numberarrNum=getNum(arrNum,tmp,minValue,maxValue,ra); //Take out the value and assign it to the array} 
......... 
......... 
public int getNum(int[] arrNum,int tmp,int minValue,int maxValue,Random ra) 
{ 
int n=0; 
while (n&lt;=-1) 
{ 
if (arrNum[n]==tmp) //Use the loop to determine whether there is any duplication{ 
tmp=(minValue,maxValue); //Re-randomly retrieve.getNum(arrNum,tmp,minValue,maxValue,ra);//Recursion: If the retrieved number and the obtained number are repeated, it will be retrieved randomly.} 
n++; 
} 
return tmp; 
}

The above is the entire content of this article, I hope you like it.