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]);
             }

             Console.ReadLine();
        }

        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);
                result.Add(nums[idx]);
                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 .
Sample of the answer is:
2
4
6
8
10
9
1
3
7
5

Why is it so??

Recommended Answers

All 4 Replies

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?

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).

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.