从范围中选择但排除某些数字

Select from a range but exclude certain numbers(从范围中选择但排除某些数字)
本文介绍了从范围中选择但排除某些数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Is it possible to pick a random number from a given range (1-90), but exclude certain numbers. The excluded numbers are dynamically created but lets say they are 3, 8, and 80.

I have managed to create random number generator but couldn't identify any functions that let me fulfill my requirements.

Random r = new Random();
this.num = r.Next(1, 90);

The numbers which are to be excluded are previously generated numbers. So, if the random number is one, this would then get added to the excluded numbers list.

解决方案

Using some handy extension methods here, you can create a range of numbers and select randomly from that rage. For example, with these extension methods:

public static T RandomElement(this IEnumerable<T> enumerable)
{
    return enumerable.RandomElementUsing(new Random());
}

public static T RandomElementUsing(this IEnumerable<T> enumerable, Random rand)
{
    int index = rand.Next(0, enumerable.Count());
    return enumerable.ElementAt(index);
}

You can apply these to a filtered range of numbers:

var random = Enumerable.Range(1, 90).Except(arrayOfRemovedNumbers).RandomElement();

这篇关于从范围中选择但排除某些数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)