Hey frenz ,
I just made a console application in C#.NET as:

``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<int> rand = new List<int>();

rand = abc();

for (int i = 0; i < 10; i++)
{
Console.WriteLine(rand[i]);
}

}

public static List<int> abc()
{

Random random = new Random();
List<int> nums = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

List<int> result = new List<int>();
while (nums.Count > 0)
{
int idx = random.Next(0, nums.Count);
nums.RemoveAt(idx);
}
return result;
}

}
}
``````

Just look at the line => int idx = random.Next(0, nums.Count);
For 1st time iteration of while loop , nums.count will be equal to 10 and so the value of idx can be 10 also . Now, if idx =10 ,
and then there is no index 10 in List nums and it should give an error . But still , my anser comes without any error .
2
4
6
8
10
9
1
3
7
5

Why is it so??

2
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by RanbirSandhu

For 1st time iteration of while loop , nums.count will be equal to 10 and so the value of idx can be 10 also

No it can't. Reread the page on Random.Next. The second parameter is the upper bound exclusive which means it goes from lower bound to one less than the upper bound, so your values can be from 0 to 9.

But friend if 2nd parameter is upper bound exclusive , when I change the code as write it as
int idx = random.Next(0, nums.Count-1);
then also it works fine.

Why is it so?

Edited by RanbirSandhu: spelling mistake

The last time through the loop you have a Random.Next of (0,0), and if you read the documentation as I sugested, you'll know that when min = max, it returns min. What this means is that
Random.Next(0, 1) is the same as Random.Next(0, 0) as both will return 0 (zero).

Edited by Momerath

thankz bro very much for help !!! :-)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.