Monday 24 November 2014

Introducing random class in c-sharp

Case Study: Rolling a six dice problem.


In this problem the application simulate 20 rolls of a six sided dice and display the value of each roll. So, in this problem we use
random class : the object of class random can produce random byte,int,double values
Scaling factor:
 int randomValue = random.Next(6);

In the above statement we use randomvalue of type integer random is the object of class "Random;", Next is the method of class random
The above statement returns value 0,1,2,3,4,5. The Argument is called Scaling factor- Represent the no. of that Next should produce (in this case 0,1,2,3,4 and 5)
This manipulation is called scaling the range of value produce by Random method Next.
Shifting factor
Suppose we want to simulate six die and that has the numbers 1-6 on its faces, not 0-5. Scaling the range of value is not enough. So we shift the range of numbers we produced. We could do this by adding shifting value – in this case 1- to the result of method next, as in
         int randomValue =1+ random.Next(6);
OR
int randomValue = random.Next(1,6);

Here we have two example of class random.

Example one: Rolling a six sided die twenty times and note the result every time
Source Code

using System;
public class RandomIntegers
{
public static void Main()
{
Random random=new Random(); // create object of Random Method
int face; //store each random integer

for(int counter=1;counter<=20;counter++)
{
face=random.Next(1,7); //shifting and scaling
Console.Write("{0} ",face); //display generated value
if(counter%5==0)
Console.WriteLine();
}

}
}

Screenshots of Output:


Application of random class. Dice game
Fig 1: Snapshot of Dice game

Example 2:  Rolling a dice 6000 time and observe the frequency of outcomes.

Source Code: 

using System;
public class RollDie
{
public static void Main()
{
Random random = new Random();

int frequency1=0; //Count of 1's rolled
int frequency2=0; //Count of 2's rolled
int frequency3=0; //Count of 3's rolled
int frequency4=0; //Count of 4's rolled
int frequency5=0; //Count of 5's rolled
int frequency6=0; //Count of 6's rolled

int face;  //store most recently rolled value

for(int roll=1;roll<=6000;roll++)
{
face=random.Next(1,7); //number from 1 to 6

switch(face)
{
case 1:
frequency1++;
break;

case 2:
frequency2++;
break;

case 3:
frequency3++;
break;

case 4:
frequency4++;
break;

case 5:
frequency5++;
break;

case 6:
frequency6++;
break;
}
}

Console.WriteLine("Face\tFrequency" ); // output headers

Console.WriteLine("1\t{0}\n2\t{1}\n3\t{2}\n4\t{3}\n5\t{4}\n6\t{5}\n",
frequency1, frequency2, frequency3, frequency4, frequency5, frequency6);
}
}

Screenshot of Final Output: 


Frequency of Dice faces.
Fig 2: Frequency of dice faces