我需要以随机顺序打印1到50之间的数字而不重复 它。
static void Main(string[] args)
{
ArrayList r = new ArrayList();
Random ran = new Random();
for (int i = 0; i < 50; i++)
{
r.Add(ran.Next(1,51));
}
for (int i = 0; i < 50; i++)
Console.WriteLine(r[i]);
Console.ReadKey();
}
答案 0 :(得分:2)
这里你想要的是Fisher Yates Shuffle
以下是由Jeff Atwood
实施的算法cards = Enumerable.Range(1, 50).ToList();
for (int i = cards.Count - 1; i > 0; i--)
{
int n = ran.Next(i + 1);
int temp = cards[i];
cards[i] = cards[n];
cards[n] = temp;
}
答案 1 :(得分:1)
如果您不想重复1到50之间的数字,最好的办法是填充数字1到50的列表然后随机播放内容。这里有一个关于洗牌的好帖子: Randomize a List<T>
答案 2 :(得分:0)
您需要做的就是检查列表中是否已存在该号码,如果是这样,请另外一个:
static void Main(string[] args)
{
ArrayList r = new ArrayList();
Random ran = new Random();
int num = 0;
for (int i = 0; i < 50; i++)
{
do { num = ran.Next(1, 51); } while (r.Contains(num));
r.Add(num);
}
for (int i = 0; i < 50; i++)
Console.WriteLine(r[i]);
Console.ReadKey();
}
编辑:这将大大提高效率,防止等待非碰撞数字的长暂停:
static void Main(string[] args)
{
List<int> numbers = new List<int>();
Random ran = new Random();
int number = 0;
int min = 1;
int max = 51;
for (int i = 0; i < 50; i++)
{
do
{
number = ran.Next(min, max);
}
while (numbers.Contains(number));
numbers.Add(number);
if (number == min) min++;
if (number == max - 1) max--;
}
for (int i = 0; i < 50; i++)
Console.WriteLine(numbers[i]);
Console.ReadKey();
}