給定一個正整數n,需要輸出一個長度為n的數組,數組元素是隨機數,范圍為0 – n-1,且元素不能重復。比如 n = 3 時,需要獲取一個長度為3的數組,元素范圍為0-2;簡單的理解就是生成一個無序的隨機數組。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomNumber
{
class Program
{
static void Main(string[] args)
{
//初始化一個數組,如果數組沒有賦值,默認是0
//int[] arr = SolveProblemWayOne(5);
//int[] arr = SolveProblemWaySecond(5);
//int[] arr = SolveProblemWayThird(10);
int[] arr = SolveProblemWayFour(5);
for (int i = 0; i < arr.Length; i++)
{
Console.Write("{0,5}", arr[i].ToString());
}
Console.ReadKey();
}
/// <summary>
/// 循環判斷隨機出來的數字是否在數組中
/// </summary>
/// <param name="total"></param>
/// <returns></returns>
public static int[] SolveProblemWayOne(int count)
{
List<int> resultList = new List<int>();
Random random = new Random();
for (int i = 0; i < count; i++)
{
int number = random.Next(1, count + 1);
while (resultList.Contains(number))
{
number = random.Next(1, count + 1);
}
resultList.Add(number);
}
return resultList.ToArray();
}
/// <summary>
/// 按照順序生成一個數組
/// </summary>
/// <param name="total"></param>
/// <returns></returns>
public static int[] SolveProblemWaySecond(int count)
{
List<int> orignalList = new List<int>();
List<int> resultList = new List<int>();
for (int i = 0; i < count; i++)
{
orignalList.Add(i);
}
int maxIndex = count;
Random random = new Random();
for (int i = 0; i < count; i++)
{
//隨機索引
int index = random.Next(0, maxIndex);
resultList.Add(orignalList[index]);
orignalList.RemoveAt(index);
maxIndex--;
}
return resultList.ToArray();
}
/// <summary>
/// 不刪除數據,然后的問題就是給最后的東西賦值
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public static int[] SolveProblemWayThird(int count)
{
List<int> orignalList = new List<int>();
List<int> resultList = new List<int>();
for (int i = 0; i < count; i++)
{
orignalList.Add(i);
}
int minIndex = 0;
Random random = new Random();
for (int i = 0; i < count; i++)
{
//隨機索引
int index = random.Next(minIndex, count);
resultList.Add(orignalList[index]);
//交換,由于索引自減,不需要將隨機的值賦值到最后
//int temp = orignalList[index];
orignalList[index] = orignalList[minIndex];
//orignalList[minIndex] = temp;
minIndex++;
}
return resultList.ToArray();
}
/// <summary>
/// 簡潔方式
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public static int[] SolveProblemWayFour(int count)
{
List<int> resultList = new List<int>();
for (int i = 0; i < count; i++)
{
resultList.Add(i);
}
int minIndex = 0;
Random random = new Random();
for (int i = 0; i < count; i++)
{
//隨機索引
int index = random.Next(minIndex, count);
//頭部交換
int temp = resultList[index];
resultList[index] = resultList[minIndex];
resultList[minIndex] = temp;
minIndex++;
}
return resultList.ToArray();
}
}
}
新聞熱點
疑難解答