This program generates Unique Random Numbers and displays them 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 who you are!
  1. class testrandom {
  2. publicstaticvoid Main(string[] args) {
  3. int intno;
  4. if (args.Length == 0) {
  5. Console.WriteLine("Please enter a parameter eg. unique 5");
  6. return;
  7. } else {
  8. intno = Int32.Parse(args[0]);
  9. if (intno < 1) {
  10. // Check to see if user has entered value >= 1 because my LowerBound is hardcoded to 1
  11. Console.WriteLine("Enter value greater than or equal to 1");
  12. return;
  13. }
  14. }
  15. unique_random generateit = new unique_random();
  16. generateit.create_random(intno);
  17. }
  18. }
  19. class unique_random {
  20. publicvoid create_random(int passed_intno) {
  21. // Remember: C# Requires all variables Initialized.... so lets initialize variable used
  22. int LowerBound = 1;
  23. int UpperBound = passed_intno;
  24. bool firsttime = true;
  25. int starti = 0;
  26. int[] vararray;
  27. vararray = newint[UpperBound];
  28. // Random Class used here
  29. Random randomGenerator = new Random(DateTime.Now.Millisecond);
  30. do {
  31. int nogenerated = randomGenerator.Next(LowerBound, UpperBound + 1);
  32. // Note: randomGenerator.Next generates no. to UpperBound - 1 hence +1
  33. // .... i got stuck at this pt & had to use the debugger.
  34. if (firsttime) // if (firsttime == true)
  35. {
  36. vararray[starti] = nogenerated; // we simply store the nogenerated in vararray
  37. firsttime = false;
  38. starti++;
  39. } else // if (firsttime == false)
  40. {
  41. bool duplicate_flag = CheckDuplicate(nogenerated, starti, vararray); // call to check in array
  42. if (!duplicate_flag) // duplicate_flag == false
  43. {
  44. vararray[starti] = nogenerated;
  45. starti++;
  46. }
  47. }
  48. }
  49. while (starti < UpperBound);
  50. PrintArray(vararray); // Print the array
  51. }
  52. publicbool CheckDuplicate(int newrandomNum, int loopcount, int[] function_array) {
  53. bool temp_duplicate = false;
  54. for (int j = 0; j < loopcount; j++) {
  55. if (function_array[j] == newrandomNum) {
  56. temp_duplicate = true;
  57. break;
  58. }
  59. }
  60. return temp_duplicate;
  61. }
  62. // Print Array
  63. publicstaticvoid PrintArray(Array arr) {
  64. Console.Write("{");
  65. int count = 0;
  66. int li = arr.Length;
  67. foreach(object o in arr) {
  68. Console.Write("{0}", o);
  69. count++;
  70. //Condition to check whether ',' should be added in printing arrray
  71. if (count < li) Console.Write(", ");
  72. }
  73. Console.WriteLine("}");
  74. }
  75. }