public float[] GetRandomNum(float[] Nums, int N) { if (Max < N) N = Max; List<int> Source = new List<int>(); List<int> Result = new List<int>(); for (int i = 0; i < Nums.Length; i++) Source.Add(Nums[i]); Random R = new Random(); for (int n = 0; n < N; n++) { int r = R.Next(0, Source.Count); Result.Add(Source[r]); Source.RemoveAt(r); } Result.Sort(); //这句可选 return Result.ToArray(); }
Random r = new Random(); r.Next(1,20); 我就是这么用的。没用。每次都会重复的。Random r = new Random(); r.Next();是生成任意的数。根本不是解决我的问题的。
首先建立一个列表ArrayList list,将其长度设为20,给其赋值,从1到20。 再随机生成一个数,Random r=new Random()。每生成一个随机数,就移走一个list中的元素 这样一来,就不会出现重复了。源码 using System; using System.Collections.Generic; using System.Text; using System.Collections;namespace RandomTest { class Program { static void Main(string[] args) { Random r = new Random(); ArrayList list = new ArrayList(20); //赋值 for (int i = 0; i < 20; i++) { list.Add(i); } for (int i = 0; i < 4; i++) { //产生0-20之间的随机数 int index = r.Next(0, list.Count); //输出产生的随机数 Console.WriteLine(list[index]); //移除已产生的随机数 list.RemoveAt(index); } Console.ReadLine(); } } } 运行结果 18 10 15 3
r.Next();
public float[] GetRandomNum(float[] Nums, int N)
{
if (Max < N) N = Max;
List<int> Source = new List<int>();
List<int> Result = new List<int>();
for (int i = 0; i < Nums.Length; i++) Source.Add(Nums[i]);
Random R = new Random();
for (int n = 0; n < N; n++)
{
int r = R.Next(0, Source.Count);
Result.Add(Source[r]); Source.RemoveAt(r);
}
Result.Sort(); //这句可选
return Result.ToArray();
}
r.Next(1,20);
我就是这么用的。没用。每次都会重复的。Random r = new Random();
r.Next();是生成任意的数。根本不是解决我的问题的。
再随机生成一个数,Random r=new Random()。每生成一个随机数,就移走一个list中的元素
这样一来,就不会出现重复了。源码
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;namespace RandomTest
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
ArrayList list = new ArrayList(20); //赋值
for (int i = 0; i < 20; i++)
{
list.Add(i);
} for (int i = 0; i < 4; i++)
{
//产生0-20之间的随机数
int index = r.Next(0, list.Count);
//输出产生的随机数
Console.WriteLine(list[index]);
//移除已产生的随机数
list.RemoveAt(index);
}
Console.ReadLine();
}
}
}
运行结果
18
10
15
3