有時候寫程式會用到亂數,
而且產生得亂數不會重複。
我用的方法是【撲克牌】法,
也就是1-52本來就已經決定,
接著兩兩對調,
對調的次數越多,
亂數的序列越均勻,
最後再從52張牌抽一張,
那個就是【撲克牌】法所產生的亂數。
而我擴增【撲克牌】法的功能,
可設定範圍 (最大, 最小) ,
GRN(n, 30, 99); 表示 (30, 99) 。
程式執行的結果:
76 95 32 51 34 88 53 37 57 79
65 81 69 77 93 80 35 47 48 96
60 33 54 36 46 43 89 68 58 71
91 42 70 38 67 64 56 78 87 52
66 62 75 85 82 40 61 55 97 59
49 41 45 84 73 72 50 92 86 63
74 99 39 90 94 44 31 30 98 83請按任意鍵繼續 . . .
程式碼如下:
/**
Theme: Generate Random Number
Compiler: Dev C++ 4.9.9.2
Date: 100/03/14
Author: ShengWen
Blog: https://cg2010studio.wordpress.com/
*/
#include<iostream>
#include<ctime>
using namespace std;
#define SIZE 100
void GRN(int* number, int small, int big);
int n[SIZE]={};
int main(){
GRN(n, 30, 99);
system("pause");
return 0;
}
void GRN(int* number, int small, int big){//產生 small~big 的亂數
srand(time(NULL));
int n1=0, n2=0, temp=0;
for(int i=0;i<big-small+1;i++){//數字分配 0~big-small
number[i]=i;
}
for(int i=0;i<big-small+1;i++){//兩兩交換
n1=rand()%(big-small+1);
n2=rand()%(big-small+1);
temp=number[n1];
number[n1]=number[n2];
number[n2]=temp;
}
for(int i=0;i<big-small+1;i++){//數字位移 small~big
number[i]+=small;
}
for(int i=0;i<big-small+1;i++){//數字列印
cout<<number[i]<<' ';
if(i%10==9)
cout<<endl;
}
cout<<endl;
}
Comments on: "[C++] 產生隨機數字且不重複 (Generate Random Number)" (1)
Your style is so unique compared to other folks I have read stuff from. I appreciate you for posting when you’ve got the opportunity, Guess I will just bookmark this page.
讚讚