C# Random – Order in Chaos

c# randomThe Random class can be used to simulate a random value to retrieve in your code. The Random class, which the System namespace encompasses, is actually based on a pseudo-random approach. Although data will be retrieved while the value remains unknown, to a program user, the Random class uses algorithms along with other variables, such as seeds, in order to complete its associated functions. Seeds are essentially values that you provide in order for a Random class to have a defined starting point for successions.

Generating Numbers

One use of the Random class is number generation. In this scenario, an organization hosting a lottery requests a program that will generate a specific amount of numbers from defined ranges. The objective in this case is to use the Random class in order to generate a set of six numbers selected from a range of 1 to 75. An example of an options that you could use is as follows:

using System;

public class Lottery
{
static void Main()
{
Random rand = new Random();

Console.WriteLine("\n*******Your Lottery Numbers:*******");
for (int set = 1; set <= 6; set++)
{
Console.Write("{0,6}", rand.Next(0, 76));

}

}
}

notes:

  • The counting object did not have to be named “set” and some writers of code choose to use a letter, such as “i”, for the counting object.
  • The object set is initialized at 1 and then continues to perform the steps within the For loop for 6 cycles.
  • I had provided the numbers 0 and 76 for the range that should be used when the sequence of numbers is being retrieved by the Random Class because the index begins at 0 and thus,76 should be the ending number in order to include the number 75 in the possible sequence.
  • The Console.Write method includes the range of values that can be written (or displayed) as well as formatting for six integers as notated by the following: “({0,6})”.
  • The seed for the example above is the current time as a parameter had not been provided for the Random class and the system clock is use for the default seed; for as long as the date and time are the same, the results of the code can be the same.

Generation of Numbers with Threading

Although the code in the first example would have resulted in 6 numbers from 1 to 75 being displayed, there are some methods to use in order to decrease the chances of the same numbers being used in one session or thread. One method to use for improving the code used in the previous example is to integrate the System.Threading namespace and utilize a Thread constructor. An example of using a Thread constructor is as follows:

using System;
using System.Threading;

public class Lottery
{
static void Main()
{
Random rand = new Random();
Thread.Sleep(1000);
Random rand2 = new Random();

}
private static void Demo (Random rand)
{
Console.WriteLine("\n*******Your Lottery Numbers:*******");
for (int set = 1; set <= 6; set++)
{
string input;
Console.Write("{0,6}", rand.Next(0, 76));
Console.WriteLine("Retrieve more numbers? Y or N");
input = Console.ReadLine();
while (input == "Y")
{
Console.Write("{0,6}", rand.Next(0, 76));
}

break;

}

}}

The Thread class is used for “blocking” a consecutive action taken with the Random class (which has been overloaded in this case) for the amount of time provided as the parameter for the Thread.Sleep instance (4 seconds in this case). If an amount of “sleep time” is used with a thread, then this is a way to disallow a Random function to retrieve the same information from the same thread. A couple of factors to note about the code above are that a different type of loop may have been used instead of the While loop and the fact that some program architectures may not allow the use of synchronization primitives, such as those that may be used by Threads. What could happen if synchronization primitives are able to initiate while also running in an environment that has not been configured to successfully handle synchronization primitives? One possibility could be Deadlocks, which can cause interruption of programs and computers to stop responding. C# can also be used for database deadlock handling, by using a framework, such as the Entity framework.

Generating Letters and Other Characters

Common uses of randomly generated characters include password generation and name generation. There are different requirements for passwords, including requirements for which types of characters are allowed in a password. The following is an example of a Random function being used for generating a password:

using System;

class Password
{
static void Main()
{

string passChars;
passChars = "a, b,c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v,
w, x, y, z";
passChars = "A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U,
V, W, X, Y, Z";
passChars = "1, 2, 3, 4, 5, 6, 7, 8, 9, 0";
passChars = "@, #, $, &, !, *";
string strPass = "";

Random rand = new Random();
for (int i=0; i <= 7; i++)
{
int iRandom = rand.Next(0, passChars.Length -1);
strPass +=passChars.Substring(iRandom, 1);

}
Console.Write("Password: {0}", strPass);
}

}

One note about the code above is that there are opportunities to enhance such code for passwords, such as by using the System.Security.Cryptography namespace. To learn more about different namespaces in C#, Udemy tutorials could be a great resource. There are some cases in which one may want to retrieve random names, such as when a book writer may want ideas for names of characters. A variable provided for name generation is a list of names and therefore, name generation possibilities will be partially dependent on the names that have been supplied. The following is an example of a Random function being used to generate a name:

using System;
class Names
{
static void Main()
{

string[] firstNames = {"Laura", "Sarah", "John", "Daniel", "Cara", "Robert",
"Francine", "Austin"};
string[] lastNames = {"Richardson", "Smith", "Franklin", "Johnson", "Brown",
"Jacobson", "Boggs", "Mcneill"};
Random rand = new Random();

int fNames = rand.Next(0, firstNames.Length);
int lNames = rand.Next(0, lastNames.Length);

Console.WriteLine("First name: {0}", firstNames[fNames]);
Console.WriteLine("Last name: {0}", lastNames[lNames]);

}
}

Summary

There are many possible uses of the Random class, which often involve generation of numbers, characters, and/or words. Considerations to take when using the Random class include possible variables or seeds that may be provided in order for Random functions to have a basis and data to use for possible output options as well as when usage of Threading may be beneficial. Although the Random functions in C# are based on pseudo-random principles, Random functions can provide an array of options that simulate random generation.