Hi Guys
NP138 Random
In the following program output 1, 2, 3, 4, 5 and 6 is coming, 7 is not coming. Please explain the reason.
Thank you
using System;
class MainClass
{
public static void Main()
{
Random ran = new Random();
Console.WriteLine(ran.Next(1, 7));
}
}
AlanPosted Aug 26, 2008, 5:18 PM
It's because the Random.Next(a, b) method produces a random integer 'x' in the range a <= x < b.
In other words, the start point is included but the endpoint is not.
Not sure why it was done this way but it's a point you need to be careful about in practice.
Posted Aug 27, 2008, 12:06 PM
Thank you very much for explanation.
AlanPosted Aug 27, 2008, 11:22 AM
The r2.Next(150000) call produces a random integer 'i' in the range:
0 <= i < 150000
so 75274 is within that range.
The r2.NextDouble() call produces a random double 'd' in the range:
0 <= d < 1
so 0.571986661558965 is within that range.
Posted Aug 27, 2008, 8:44 AM
Thank you for explanation.
How this can be explained?
Console.WriteLine(r2.Next(150000)); //75274
Console.WriteLine(r2.NextDouble()); //0.571986661558965
AlanPosted Aug 26, 2008, 7:19 PM
The number passed to the Random constructor is what's called a 'seed' value. This is simply a starting value from which the pseudo-random sequence of random numbers will be generated - it is nothing to do with the range of those numbers.
So, in the first example, calling Random.Next() without an argument can produce any random integer between 0 and int.MaxValue - 1 (2,147,483,646) inclusive. The number produced (214,873,035) is, of course, well within that range.
Posted Aug 26, 2008, 5:39 PM
How can output of the following program be explained? Note that Random() constructor is holding a number 99830123.
using System;
//using System.Collections.Generic;
//using System.Globalization;
//using System.IO;
//using System.Text;
public class MainClass
{
public static void Main()
{
Random r2 = new Random(99830123);
Console.WriteLine(r2.Next()); //214873035
Console.WriteLine(r2.Next(150000)); //75274
Console.WriteLine(r2.Next(9999, 100750)); //85587
Console.WriteLine(r2.NextDouble()); //0.571986661558965
}
}