using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace RandTest{ class Program { static void Main(string[] args) { int m; do { Console.WriteLine("请输入要产生随机数的数量(大于0的数字):"); } while (!int.TryParse(Console.ReadLine(), out m)); int limit; do { Console.WriteLine("请输入随机数的最大范围(大于0的数字并且要大于要产生随机数的数量):"); } while (!(int.TryParse(Console.ReadLine(), out limit) && limit >= m)); RandomNumbers(m, limit); Console.WriteLine(); genknuth(m, limit); Console.WriteLine(); randselect(m, limit); Console.WriteLine(); genshuf(m, limit); Console.ReadKey(); } ////// 产生0~limit(大于等于0少于limit)内的m个随机数 /// /// 随机数的数量 /// 随机数的最大范围(limit>=m) static void RandomNumbers(int m,int limit) { int[] temp = new int[limit]; for (int i = 0; i < limit; i++) temp[i] = i; int number = 0; int count = 0; Random rand = new Random(); for (int i = 1; i <= m; i++) { number = rand.Next() % limit; while (temp[number] == -1) { number = rand.Next() % limit; } Console.Write(temp[number] + "\t"); count++; if (count % 10 == 0) { Console.WriteLine(Environment.NewLine); } temp[number] = -1; } } static void genknuth(int m, int limit) { int i; Random d = new Random(); for (i = 0; i < limit; i++) if (d.Next() % (limit - i) < m) { Console.WriteLine(i); m--; } } static void randselect(int m, int limit) { int r; Random d = new Random(); if (m > 0) { r = d.Next() % limit; if (r < m) { Console.WriteLine(limit - 1); randselect(m - 1, limit - 1); } else randselect(m, limit - 1); } } static void genshuf(int m, int limit) { int i, j; int[] x = new int[limit]; for (i = 0; i < limit; i++) x[i] = i; Random d = new Random(); for (i = 0; i < m; i++) { j = d.Next(i, limit - 1); int t = x[i]; x[i] = x[j]; x[j] = t; } for (i = 0; i < m; i++) Console.WriteLine(x[i]); } }}
refer to:
思考:该算法就是用空间来换时间,如果每次产生一个随机数都和前面产生的比较的话,将耗费大量的时间。这样产生的话 如果要产生的个数接近区间长度 那产生最后几个的时候可能会花很多很多时间。还有一种思路:可以先对区间内的数shuffle一下,然后需要多少个就去前多少个。shuffle有快速的算法
还有什么更好的,大家都说说哈O(∩_∩)O~