给定一个正整数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();
}
}
}
新闻热点
疑难解答