Showing posts with label Random. Show all posts
Showing posts with label Random. Show all posts

January 22, 2016

Random Extension

An extension to the Random class to help convert the random number generator class to generate more than just integers. It is very simple to use, pass your array of random choices as parameters to the method.
Hint: Make your Random instance static so that the choice of random values is not continually reset back to the start.
private static Random random = new Random();
...
/// <summary>
/// An extension to the Random class to help convert the random generator to 
/// generate more than just integers. It is very simple to use, pass your 
/// array of random choices as parameters to the method.
/// </summary>
/// <example>
/// For example, say you want something chosen at random from the following 
/// set of football teams:
/// "Liverpool", "Southampton", "Manchester United", "Barcelona"
/// then use the following line: 
/// string randomTeam = random.NextFromSet<T>("Liverpool", 
///                      "Southampton", "Manchester United", "Barcelona");
/// </example>
public static class RandomExtensions
{
 public static T NextFromSet<T>(this Random random, params T[] set)
 {
  return set[random.Next(0, set.Length)];
 }
}

...
string randomTeam = random.NextFromSet<string>("Liverpool", "Southampton", 
      "Manchester United", "Barcelona");

August 16, 2008

Random Number Generator

Random class in .Net is part of System namespace
//Declare an object
Random randomNumberGenerator = new Random();
random.NextDouble() //to get the next random number between 0.0 and 1.0;
random.Next() // to get the next random positive integer number
// to get the next random integer, x where  'upper' <= x  < 'lower'
random.Next(lower, upper) 
Byte[] b = new Byte[10];
random.NextBytes(b); to set an array of bytes

//To set a seed for the random number generator
int seed = 137;
System.Random randomNumberGenerator = new System.Random(seed);