How do I store a random number into my array, but only if there is not a duplicate already inside the array? My code below still inputs a duplicate number.
如何在数组中存储一个随机数,但前提是数组中已经没有副本了?我下面的代码仍然输入一个重复的数字。
Random rand = new Random();
int[] lotto = new int [6];
for (int i = 0; i < lotto.Length; i++)
{
int temp = rand.Next(1, 10);
while (!(lotto.Contains(temp)))//While my lotto array doesn't contain a duplicate
{
lotto[i] = rand.Next(1, 10);//Add a new number into the array
}
Console.WriteLine(lotto[i]+1);
}
2 个解决方案
#1
4
Try this:
试试这个:
Random rand = new Random();
int[] lotto = new int[6];
for (int i = 0; i < lotto.Length; i++)
{
int temp = rand.Next(1, 10);
// Loop until array doesn't contain temp
while (lotto.Contains(temp))
{
temp = rand.Next(1, 10);
}
lotto[i] = temp;
Console.WriteLine(lotto[i] + 1);
}
This way the code keeps generating a number until it finds one that isn't in the array, assigns it and moves on.
这样,代码就会一直生成一个数字,直到找到一个不在数组中的数字,分配它,然后继续。
There are a lot of ways to 'shuffle' an array, but hopefully this clears up the issue you were having with your code.
有很多方法可以“洗牌”数组,但希望这能解决您在代码中遇到的问题。
#2
1
What you really want is to shuffle the numbers from 1 to 9 (at least that's what your example is implying) and then take the first 6 elements. Checking for duplicates is adding unnecessary indeterminism and really is not needed if you have a shuffle.
你真正想要的是把数字从1到9(至少是你的例子所暗示的),然后取前6个元素。检查重复是否增加了不必要的不确定性,如果你进行了洗牌,实际上是不需要的。
E.g take this accepted answer for a Fisher-Yates shuffle and then take the first 6 elements for lotto
.
E。g接受这个公认的答案,对鱼-耶茨洗牌,然后取第6个元素的乐透。
This would then look like this:
这个看起来是这样的:
lotto = Enumerable.Range(1,9)
.Shuffle()
.Take(6)
.ToArray();
#1
4
Try this:
试试这个:
Random rand = new Random();
int[] lotto = new int[6];
for (int i = 0; i < lotto.Length; i++)
{
int temp = rand.Next(1, 10);
// Loop until array doesn't contain temp
while (lotto.Contains(temp))
{
temp = rand.Next(1, 10);
}
lotto[i] = temp;
Console.WriteLine(lotto[i] + 1);
}
This way the code keeps generating a number until it finds one that isn't in the array, assigns it and moves on.
这样,代码就会一直生成一个数字,直到找到一个不在数组中的数字,分配它,然后继续。
There are a lot of ways to 'shuffle' an array, but hopefully this clears up the issue you were having with your code.
有很多方法可以“洗牌”数组,但希望这能解决您在代码中遇到的问题。
#2
1
What you really want is to shuffle the numbers from 1 to 9 (at least that's what your example is implying) and then take the first 6 elements. Checking for duplicates is adding unnecessary indeterminism and really is not needed if you have a shuffle.
你真正想要的是把数字从1到9(至少是你的例子所暗示的),然后取前6个元素。检查重复是否增加了不必要的不确定性,如果你进行了洗牌,实际上是不需要的。
E.g take this accepted answer for a Fisher-Yates shuffle and then take the first 6 elements for lotto
.
E。g接受这个公认的答案,对鱼-耶茨洗牌,然后取第6个元素的乐透。
This would then look like this:
这个看起来是这样的:
lotto = Enumerable.Range(1,9)
.Shuffle()
.Take(6)
.ToArray();