我试图用 1-10 的随机数填充一个数组,不重复。我尝试用递归来做到这一点。我正在尝试使用递归和不使用(这里两者都有,两种方式都没有运气)。我有两个代码,两者都不起作用:
1:
static int reco(int arr,int[] times)
{
Random rnd = new Random();
arr = rnd.Next(1, 11);
return times[arr] > 0 ? reco(arr, times) : arr;
}
static void Main(string[] args)
{
int i = 0;
int[] arr = new int[10];
int[] times = new int[11];
Random rnd = new Random();
for (i = 0; i < 10; i++)
{
arr[i] = rnd.Next(1, 11);
times[arr[i]]++;
if (times[arr[i]] > 0)
arr[i] = reco(arr[i], times);
}
2:
static int reco(int arr,int[] times)
{
Random rnd = new Random();
arr = rnd.Next(1, 11);
if (times[arr] > 0)
return reco(arr, times);
else
return arr;
}
static void Main(string[] args)
{
int i = 0;
int[] arr = new int[10];
int[] times = new int[11];
Random rnd = new Random();
for (i = 0; i < 10; i++)
{
arr[i] = rnd.Next(1, 11);
if (times[arr[i]] > 0)
arr[i] = reco(arr[i], times);
times[arr[i]]++;
}
}