如何制作数组中永不重复的随机数
本文关键字:随机数 何制作 数组 | 更新日期: 2024-06-14 02:49:58
listBox1.Items.Clear();
int[] sayısal = new int[6];
Random rastgele = new Random();
for (int i = 0; i < 6; i++)
{
do
{
sayısal = rastgele.Next(1, 50);
}
while (listBox1.Items.IndexOf(sayısal) != -1);
listBox1.Items.Add(sayısal);
}
当我这样做时,我收到一个错误,调用
"无法将类型'int'隐式转换为'int[]' ">
在行"sayısal = rastgele.Next(1, 50);"
.我能为它做什么?
您可以生成序列1..50
并对其进行洗牌(即按随机值排序(:
Random rastgele = new Random();
int[] sayısal = Enumerable.Range(1, 50) // generate sequence
.OrderBy(i => rastgele.Next()) // shuffle
.Take(6) // if you need only 6 numbers
.ToArray(); // convert to array
您的代码不起作用,因为您正在尝试将生成的项分配给数组变量。
sayısal = rastgele.Next(1, 50);
它应该是:
do {
sayısal[i] = rastgele.Next(1, 50);
} while(listBox1.Items.IndexOf(sayısal[i]) != -1);
正如我在评论中已经指出的那样,最好将 UI 逻辑和数组生成分开。 即
// generate array (optionally move to separate method)
int itemsCount = 6;
int[] items = new int[itemsCount]; // consider to use List<int>
Random random = new Random();
int item;
for(int i = 0; i < itemsCount; i++)
{
do {
item = random.Next(1, 50);
} while(Array.IndexOf(items, item) >= 0);
items[i] = item;
}
// display generated items
listBox1.Items.Clear();
for(int i = 0; i < items.Length; i++) // or use foreach
listBox1.Items.Add(items[i]);
因为Random.Next
方法返回int
,而不是int[]
。并且从int[]
到int
没有隐含的融合.
Return Value
Type: System.Int32
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.
如果你想填充你的数组,你可以使用像lazyberezovsky提到的Enumerable.Range
。
此方法采用整数数组并随机排序。因此,用循环填充数组,然后使用它对数组进行随机排序。您应该归功于其他人之一,因为他们是第一个发布有效答案的人。我只是认为另一种方法会很好。
数量是您希望数组随机化的次数。数字越大,数字随机的可能性就越大。
private Random random = new Random();
private int[] randomizeArray(int[] i, int amount)
{
int L = i.Length - 1;
int c = 0;
int r = random.Next(amount);
int prev = 0;
int current = 0;
int temp;
while (c < r)
{
current = random.Next(0, L);
if (current != prev)
{
temp = i[prev];
i[prev] = i[current];
i[current] = temp;
c++;
}
}
return i;
}
在选择数据结构和算法时要小心,选择错误的一个,你最终会得到 O(n^2(。恕我直言,一个合理的解决方案是一个类型化的哈希表(即字典(,它将为您提供 O(n(:
Random rnd = new Random();
var numbers = Enumerable
.Range(1, 1000000)
.Aggregate(new Dictionary<int, int>(), (a, b) => {
int val;
do {val = rnd.Next();} while (a.ContainsKey(val));
a.Add(val, val);
return a;
})
.Values
.ToArray();
仍然不理想,因为性能取决于数组大小明显小于可用数字集,并且无法检测到何时不满足此条件(或者更糟的是,当它更大时,在这种情况下,算法将进入无限循环(。