我有困難,因爲該程序似乎工作,但被困在開發和顯示最終數組。它應該有45個元素,每個編號爲1-45,但是以隨機順序生成,沒有重複。c#數組超時錯誤
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]);
}
}
}
}
它應該檢查元素來檢查數組中每個元素生成後的重複項。提示更好的方法來解決這個問題?
爲什麼不從數字1-45開始數組然後再加擾呢? –
需要隨機生成每個數字,然後將其添加到數組中。 – PotatoFries
@PotatoFries - 你爲什麼這麼說?它並沒有在「摘要」中說。 – Enigmativity