随机填充数组,不重复 [英] Filling an array randomly with no repetitions
本文介绍了随机填充数组,不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用 1-10 的随机数填充一个数组,没有重复.我尝试用递归来做到这一点.我正在尝试使用递归和不使用它(这里两者都有,两种方式都没有运气).我有两个代码,都不起作用:
I'm trying to fill an array with random numbers from 1-10 with no repeat. I try to do it with recursion. I'm trying to it with recursion and without (here is both with, no luck in either way). I have two codes, boths not working:
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]]++;
}
}
推荐答案
如果你只想要 1 到 10 之间的随机数,你可以使用 Enumerable.Range
并随机排序.
If you just want random numbers between 1 and 10, you could just use Enumerable.Range
and order randomly.
var ran = new Random();
int[] randomArray = Enumerable.Range(1, 10).OrderBy(x => ran.Next()).ToArray();
这篇关于随机填充数组,不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文