位置:长沙达内IT教育培训学校 > 学校动态 > C#中生成随机不重复数列的算法
给定一个正整数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();
}
///
/// 循环判断随机出来的数字是否在数组中
///
///
///
public static int[] SolveProblemWayOne(int count)
{
List resultList = new List();
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();
}
///
/// 按照顺序生成一个数组
///
///
///
public static int[] SolveProblemWaySecond(int count)
{
List orignalList = new List();
List resultList = new List();
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();
}
///
/// 不删除数据,然后的问题就是给较后的东西赋值
///
///
///
public static int[] SolveProblemWayThird(int count)
{
List orignalList = new List();
List resultList = new List();
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();
}
///
/// 简洁方式
///
///
///
public static int[] SolveProblemWayFour(int count)
{
List resultList = new List();
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();
}
}
}
尊重原创文章,转载请注明出处与链接:http://www.peixun360.com/1684/news/496203/违者必究! 以上就是长沙达内IT教育培训学校 小编为您整理 C#中生成随机不重复数列的算法的全部内容。