Reader Level:
ARTICLE

Generate Unique Number in C#

Posted by Nanu Jogi Articles | C# Language January 09, 2000
Generate a unique number using random class and display it on the console.
  • 0
  • 0
  • 57628

This program generates Unique Random Numbers and displays on the console.

Editor Used: Antechinus, http://www.c-point.com.

Debugger: dbgurt.exe

Thanks Saurabh for help and guidance and thanks Mahesh for loading my tutorial. And of course thanks to you for reading it you know better who you are :)

class testrandom
{
public static void Main(string[] args)
{
int intno;
if (args.Length == 0)
{
Console.WriteLine ("Please enter a parameter eg. unique 5");
return;
}
else
{
intno = Int32.Parse (args[0]);
if (intno < 1)
{
// Check to see if user has entered value >= 1 because my LowerBound is hardcoded to 1
Console.WriteLine ("Enter value greater than or equal to 1" );
return;
}
}
unique_random generateit =
new unique_random();
generateit.create_random(intno);
}
}
class unique_random
{
public void create_random (int passed_intno)
{
// Remember: C# Requires all variables Initialized.... so lets initialize variable used
int
LowerBound = 1;
int UpperBound = passed_intno;
bool firsttime = true;
int starti = 0;
int[] vararray;
vararray =
new int[UpperBound];
// Random Class used here
Random randomGenerator = new Random (DateTime.Now.Millisecond);
do
{
int nogenerated = randomGenerator.Next(LowerBound, UpperBound+1);
// Note: randomGenerator.Next generates no. to UpperBound - 1 hence +1
// .... i got stuck at this pt & had to use the debugger.
if (firsttime) // if (firsttime == true)
{
vararray[starti] = nogenerated;
// we simply store the nogenerated in vararray
firsttime =
false;
starti++;
}
else // if (firsttime == false)
{
bool duplicate_flag = CheckDuplicate(nogenerated, starti, vararray); // call to check in array
if (!duplicate_flag) // duplicate_flag == false
{
vararray[starti] = nogenerated;
starti++;
}
}
}
while (starti < UpperBound);
PrintArray (vararray);
// Print the array
}
public bool CheckDuplicate (int newrandomNum, int loopcount, int [] function_array)
{
bool temp_duplicate = false;
for (int j = 0; j < loopcount; j++)
{
if (function_array[j] == newrandomNum)
{
temp_duplicate =
true;
break;
}
}
return temp_duplicate;
}
// Print Array
public static void PrintArray(Array arr)
{
Console.Write ("{");
int count = 0;
int li = arr.Length;
foreach (object o in arr)
{
Console.Write("{0}", o);
count++;
//Condition to check whether ',' should be added in printing arrray
if (count < li)
Console.Write(", ");
}
Console.WriteLine ("}");
}
}

COMMENT USING