在循环中生成随机数而不重复。 [英] Generate random numbers in loop without repeating.

查看:94
本文介绍了在循环中生成随机数而不重复。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成随机数而不重复给定目标中的任何数字,如(1-5000)应该没有修复,我应该能够获得5000个随机数。我应该可以根据用户的需要随机运行多次,如何处理C#?



样品

目标是(1-10)

没有时间跑= 2



首次运行:

5, 4,6,8,3,1,2,0,7,10

第二轮

6,3,5,8,4,2,0,1 ,10,7



像这样,我应该能够在运行时多次获得结果..

How to generate Random numbers without repeating any numbers in the given target like(1-5000) there should be no reparation and I should be able to get 5000 randomized numbers. I should be able to run the randomized as many times as the user wants,How to do with C#?.

For Sample
Target is (1-10)
No of times to run =2

First run:
5,4,6,8,3,1,2,0,7,10
second run
6,3,5,8,4,2,0,1,10,7

Like this I should be able to get the results as many times as I run..

推荐答案

我相信下面链接的提示涵盖了你的目标。



如何生成许多随机的各种数字?



我建议寻找在替代方案1
I believe the tip linked below covers what you are after.

How to generate many random various numbers?

I recommend looking at alternative 1


请参阅我的提示:从牌组中随机抽取5张牌 [ ^ ],它是 C ++ 但是你应该明白这个想法。
See my tip: "Random extraction of 5 cards from a deck"[^], it is C++ but you should get the idea.


第一个解决方案可能有效,但是已经选择的数字越多,它就会变慢。 (毕竟,在选择了4999个数字之后,只有一种可能性,但它可能会产生任何价值,需要再次尝试,并且再一次又一次)。



可能使速度更快的一件事是使用HashSet而不是列表,因为在HashSet中搜索更快。但我真正的解决方案是不同的。



首先我们创建一个列出所有可能值的列表。

The first solution may work, but it will start to become slower the more numbers were already chosen. (after all, after having 4999 numbers selected there is only one possibility, but it may be generating any value, needing to try again, and again, and again).

One thing that may make it faster is using a HashSet instead a list, as searching in a HashSet is faster. But my real solution is different.

First we create a list which all possible values.
List<int> available = new List<int>(5000);
for(int i=1; i<=5000; i++)
  available.Add(i);





然后,我们将继续生成随机索引(而不是随机值)。这些索引将用于从可用列表中获取值,将其放入结果中,然后将其从可用列表中删除。



Then, we will keep generating random indexes (instead of random values). Such indexes will be used to get the value from the available list, put it in the result and then remove it from the available list.

List<int> result = new List<int>(5000);
while(available.Count > 0)
{
  int index = random.Next(availableCount);
  result.Add(available[index]);
  available.RemoveAt(index);
}

return result;





这样,如果你创建一个包含100万个值的列表,你将只有100万次调用 random.Next();

当然,列表本身也有其自身的问题,但最好还是等到最后一个可用的数字被猜测。



This way, if you create a list with 1 million values, you will have only 1 million calls to random.Next();
Surely the list itself has its own problems, but it is better than keep waiting until the last available number is guess.


这篇关于在循环中生成随机数而不重复。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆