如何从一个范围得到的随机数,不包括一些值 [英] How to get a random number from a range, excluding some values
本文介绍了如何从一个范围得到的随机数,不包括一些值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,我如何才能从一个值范围的随机数 - 像1..100,但这个数字不应该是价值观的一些具体名单,如5,7,17,23
解决方案
由于没有人已发布任何例如code:
私人诠释GiveMeANumber()
{
VAR排除=新的HashSet< INT>(){5,7,17,23};
无功范围= Enumerable.Range(1,100)。凡(ⅰ= GT;!exclude.Contains(ⅰ)); VAR兰特=新System.Random();
INT指数= rand.Next(0,100 - exclude.Count);
返回range.ElementAt(索引);
}
下面是思维:
- 构建数字HashSet的要排除
- 创建所有这一切都没有你的号码有位LINQ的排除列表中的数0-100的集合。
- 创建一个随机的对象。
- 使用Random对象给你和0之间的数中的数的范围内的元素的数量(含)。
- 返回的数量索引。
In C#, how do I get a random number from a range of values - like 1..100, but that number should not be in some specific list of values, like 5, 7, 17, 23?
解决方案
Since no-one has posted any example code:
private int GiveMeANumber()
{
var exclude = new HashSet<int>() { 5, 7, 17, 23 };
var range = Enumerable.Range(1, 100).Where(i => !exclude.Contains(i));
var rand = new System.Random();
int index = rand.Next(0, 100 - exclude.Count);
return range.ElementAt(index);
}
Here's the thinking:
- Build a Hashset of numbers you want to exclude
- Create a collection of all the numbers 0-100 which aren't in your list of numbers to exclude with a bit of LINQ.
- Create a random object.
- Use the Random object to give you a number between 0 and the number of elements in your range of numbers (inclusive).
- Return the number at that index.
这篇关于如何从一个范围得到的随机数,不包括一些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文