SoFunction
Updated on 2025-03-04

No duplicate random number code


/// <summary>
/// Generate a random number without repetition
/// </summary>
/// <param name="num">number</param>
/// <param name="minValue">Minimum number</param>
/// <param name="maxValue">Maximum number</param>
/// <returns>Array</returns>
public int[] getNum(int num, int minValue, int maxValue)
{
Random ra = new Random(unchecked((int)));
int[] arrNum = new int[num];//Note: The initial value of each element in the array is 0, and it must be processed separately when 0 is within the value range.
int tmp = 0;
for (int i = 0; i < num; i++)
{
tmp = getRandomNum(tmp, minValue, maxValue, ra);//Take out the value and assign it to the array

if ((arrNum, tmp) < 0)//Judge whether it exists or not, if it does not exist, the index of the element tmp should be -1
{
arrNum[i] = tmp;
}
else
{
i = i - 1;
}
}
return arrNum;
}
public int getRandomNum(int tmp, int minValue, int maxValue, Random ra)
{
tmp = (minValue, maxValue);
return tmp;
}