C# 生成依赖于2个列表的编号
下面是一些简单的代码来说明我的问题:C# 生成依赖于2个列表的编号,c#,C#,下面是一些简单的代码来说明我的问题: void method() { for(int i = 0;i<=99) { method1(); method2(); } } void method1() { if(Randombool()) { bool exists = true; int n; while(exists) { n=RandNu
void method()
{
for(int i = 0;i<=99)
{
method1();
method2();
}
}
void method1()
{
if(Randombool())
{
bool exists = true;
int n;
while(exists)
{
n=RandNum(100);
exists = list1.Exists(num => num == n);
}
list1.add(n);
}
}
void method2()
{
int n;
bool exists = true;
bool exists2 = true;
while(!(exists && !exists2))
{
n = RandNum(100);
exists = list1.Exists(elem => elem == n);
exists2 = list2.Exists(elem => elem == n);
}
list2.add(n)
}
void方法()
{
for(int i=0;i num==n);
}
列表1.添加(n);
}
}
void方法2()
{
int n;
布尔存在=真;
bool exists2=真;
而(!(exists&!exists2))
{
n=RandNum(100);
exists=list1.exists(elem=>elem==n);
exists2=list2.Exists(elem=>elem==n);
}
列表2.添加(n)
}
很明显,它将在method2的循环中停留很长一段时间
有没有一种更温和的方法来生成数字,这样我就可以避免等待?似乎您正在尝试生成一个由N个数字组成的随机序列。这里使用的方法是获取一个随机数,如果它是您已经拥有的,则丢弃它
你想做的是可以合理有效地完成的事情。只需在列表中填入0、1、2。。。按顺序,然后洗牌
从上述链接复制的伪代码:
To shuffle an array a of n elements (indices 0..n-1):
for i from n − 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
是我,还是你的代码只循环100次,你在寻找200个唯一的数字,而你的RandNum只生成0到100。此代码将不起作用。你有一些逻辑错误。如果它真的有效,我建议您使用一个哈希表()来存储数字,这样查找就会很快?你的代码甚至不是有效的c。