I'm currently trying to create a program that generates random numbers between 1 and 45 with no duplicates. My program works when I run it without the else statement whenever a duplicate comes up it inputs the number 0, when I use the else statement the function breaks. I want to display random numbers between 1 and 45 however the variable size must dictate the size of the array. For example random integers between 1 and 45 with an array size of 35.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomArray
{
public class RandomArrayNoDuplicates
{
static void Main(string[] args)
{
int size = 45;
int[] noDuplicateArray = new int[size];
noDuplicateArray = InitializeArrayWithNoDuplicates(size);
DisplayArray(noDuplicateArray);
ExitProgram();
} //end Main
static Random rng = new Random();
/// <summary>
/// Creates an array with each element a unique integer
/// between 1 and 45 inclusively.
/// </summary>
/// <param name="size"> length of the returned array < 45
/// </param>
/// <returns>an array of length "size" and each element is
/// a unique integer between 1 and 45 inclusive </returns>
///
static void ExitProgram()
{
Console.Write("\n\nPress any key to exit program: ");
Console.ReadKey();
}//end ExitProgram
public static int[] InitializeArrayWithNoDuplicates(int size)
{
int number;
int[] noDuplicates = new int[size];
for (int i = 0; i < size; i++)
{
number = rng.Next(1, size);
if (!noDuplicates.Contains(number))
noDuplicates[i] = number;
// else
// i--;
}
return noDuplicates;
}
static void DisplayArray(int[] noDuplicates)
{
foreach (int element in noDuplicates)
{
Console.Write("\t" + element + "\n");
}
}
}
}
The issue lies in this bit of code:
public static int[] InitializeArrayWithNoDuplicates(int size)
{
int number;
int[] noDuplicates = new int[size];
for (int i = 0; i < size; i++)
{
number = rng.Next(1, size);
if (!noDuplicates.Contains(number))
noDuplicates[i] = number;
// else
// i--;
}
return noDuplicates;
but I'm unsure how to fix it. I would prefer to use the random.next function rather than using enumberable approach. Thanks