I'm having difficulties since the program seems to work but gets stuck on developing and displaying the final array. It should have 45 elements each number 1 - 45 but generated in a random order with no duplicates.
using System;
namespace RandomArray
{
public class RandomArrayNoDuplicates
{
static Random rng = new Random();
static int size = 45;
static void Main()
{
int [] array = InitializeArrayWithNoDuplicates(size);
DisplayArray(array);
Console.ReadLine();
}
/// <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>
public static int[] InitializeArrayWithNoDuplicates(int size)
{
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
int number = rng.Next(1, size + 1);
arr[i] = number;
if (i > 0)
{
for (int j = 0; j <= i; j++)
{
if (arr[j] == arr[i])
{
i = i - 1;
}
else if (arr[i] != arr[j])
{
arr[i] = number;
}
}
}
}
return arr;
}
public static void DisplayArray(int[] arr)
{
for (int x = 0; x < size; x++)
{
Console.WriteLine(arr[x]);
}
}
}
}
It should check through element to check for duplicates after each element in the array is generated. Tips on a better way to approach this?