I have to generate random 100
integers from an array belonging to the interval [0 .. 132]
and i have to output those which do not belong to the interval (26 .. 100]
I don't know how to output those which do not belong to the interval. I hope someone can give me some guidance. I'm struggling to find information on internet
My first part of the code is:
Random rand = new Random();
for (int i=1; i <=100; i )
{
int x = rand.Next(0, 132);
}
CodePudding user response:
Instead of generating random numbers which you don't use, generate the ones you need directly:
Random rand = new Random();
for (int i=1; i <=100; i )
{
int x = rand.Next(0, 26-0 132-101);
if (x>26) x =101-26;
}
If the ranges get more complicated, you could use LINQ to construct a concatentation of ranges and take a random from there:
Random rand = new Random();
var nums = Enumerable.Range(0,27).Concat(Enumerable.Range(101,32));
for (int i=1; i <=100; i )
{
int x = nums.Skip(rand.Next(0,nums.Count())).First();
}
Don't do that for large ranges. According to @Dmitry Bychenko it can become very slow.
You can also use an if
statement as suggested in many comments. But then you need to count the valid numbers and use a while
loop instead of a for
loop:
Random rand = new Random();
var count = 0;
while (count < 100)
{
int x = rand.Next(0, 132);
if (x <= 26 || x > 100)
{
count ;
}
}
CodePudding user response:
Method 1. Using if
selection statement
Just check that x
value is more than 100 OR value is less than 27:
if (x < 27 || x > 100)
{
Console.WriteLine(x);
}
Method 2. Using Enumerable.Range
LINQ method
Generate range and check that x
value does NOT include in specified range:
if (!Enumerable.Range(27, 100).Contains(x))
{
Console.WriteLine(x);
}
WARNING: Using this method with large range can have a significant impact on increasing the execution time.