This question already has an answer here:
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.
Your latest update, which implies that each value can only be selected once, makes the problem easy.
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:
You can apply these to a filtered range of numbers:
Create a container which holds the numbers you do not want:
Then use do something like:
Make sure
excludedNumbers
is aHashSet
for best performance.Might not be the best choice but you can use a while loop to check the numbers you don't want
For much numbers you can use an array or a list and loop through them