### 問題描述
**如何生成位于0到n-1之間的k個不同的隨機順序的隨機整數?**(來源于**《編程珠璣》第2版**的第1章中第7頁習題4)
### 方法1
在使用Random類時,每次選擇不同的隨機因子并在Next中劃定范圍。這種方法簡單容易實現,看上去似乎是可以滿足需求的,但我不知道怎么去證明
~~~
static void GenRandoInt1(int n , int [] array, int range);
void Main(string[] args){
int n = 1000000;
int[] array = new int[n];
int range = 5000000;
GenRandomInt1(n, array, range);
Console.ReadKey();
}
void GenRandomInt1(int n, int[] array, int range){
?Random random;
for (int i = 0; i < n; i++){
random = new Random(DateTime.Now.Millisecond + i);
array[i] = random.Next(0, range);
random = null;
}
}
~~~
### 方法2
使用內置的HashSet容器,在每一次獲取范圍內隨機數時判斷容器內是否已經存在有這個隨機數,如果存在就重新算一個隨機數。
~~~
static void GenRandomInt1(int n, int[] array, int range);
static void GenRandomInt2(int n, int range, HashSet<int> hashArray);
void Main(string[] args){
int n = 1000000;
int[] array = new int[n];
int range = 5000000;
HashSet<int> hashArray = new HashSet<int>();
GenRandomInt1(n, array, range);
GenRandomInt2(n, range, hashArray);
Console.ReadKey();
}
void GenRandomInt2(int n, int range, HashSet<int> hashArray){
Random random = new Random();
int i = 0;
for (i = 0; i < n; i++){
int temp;
do {
temp = random.Next(0, range);
} while (hashArray.Contains<int>(temp));
hashArray.Add(temp);
}
}
void GenRandomInt1(int n, int[] array, int range){
Random random;
for (int i = 0; i < n; i++){
random = new Random(DateTime.Now.Millisecond + i);
array[i] = random.Next(0, range);
random = null;
}
}
~~~
網上還有一種不用hash的方法,遞歸判斷數組中是否存在已有的隨機數,在這里就不多寫。
### 方法3
找一個gcd(n,m)==1的數m,設一個起點x,那么x=(x+m)%n可以將所有的小于n的數遍歷,為了產生視覺更加隨機的感覺,可以把方程寫為x=(x+m*p)%n,p這里是個素數。利用這個公式可以產生等概率而且不重復的k個隨機值。
### 書上答案
~~~
for i = [0, n)
x[i] = i
for i = [0,n)
swap(i, randint(i, n-1))
print x[i]
~~~
**轉載請注明出處**:[http://blog.csdn.net/utimes/article/details/8761541](http://blog.csdn.net/utimes/article/details/8761541)
- 前言
- 螺旋矩陣、螺旋隊列算法
- 程序算法藝術與實踐:稀爾排序、冒泡排序和快速排序
- Josephu 問題:數組實現和鏈表實現
- 楊輝三角形算法
- 位圖排序
- 堆排序的實現
- Juggling算法
- 【編程珠璣】排序與位向量
- 取樣問題
- 變位詞實現
- 隨機順序的隨機整數
- 插入排序
- 二分搜索
- 產生不重復的隨機數
- 約瑟夫環解法
- 快速排序
- 旋轉交換或向量旋轉
- 塊變換(字符反轉)
- 如何優化程序打印出小于100000的素數
- 基本的排序算法原理與實現
- 利用馬爾可夫鏈生成隨機文本
- 字典樹,后綴樹
- B-和B+樹
- 程序算法藝術與實踐引導
- 程序算法藝術與實踐:基礎知識之有關算法的基本概念
- 程序算法藝術與實踐:經典排序算法之桶排序
- 程序算法藝術與實踐:基礎知識之函數的漸近的界
- 程序算法藝術與實踐:遞歸策略之矩陣乘法問題
- 程序算法藝術與實踐:遞歸策略之Fibonacci數列
- 程序算法藝術與實踐:遞歸策略基本的思想
- 程序算法藝術與實踐:經典排序算法之插入排序
- 程序算法藝術與實踐:遞歸策略之遞歸,循環與迭代