執行結果
//產生 n 位不重複隨機數
//generate N-bit not repeat the random number
#include <cstdlib>
#include <iostream>
#include <windows.h>
using namespace std;
int getRandom(int,int);
int main(int argc, char *argv[]){
int i,n,nums[10],randNum[10];
//initial value=-1
cout << "initial value=-1" << endl;
for(i=0;i<10;i++){
nums[i]=-1;
}
//generate rand number by i
cout << "generate rand number by i..." << endl;
for(i=0;i<10;i++){
Sleep(57);
n=getRandom(0,9);
printf("nums[%d]=%d",n,nums[n]);
if(nums[n]<0){
nums[n]=i;
printf("\tSet %d\n",i);
}else{
while(true){
Sleep(91);
n=getRandom(0,9);
printf("\n |-- nums[%d]=%d",n,nums[n]);
if(nums[n]<0){
printf("\tset %d\n",i);
nums[n]=i;
break;
}
}
}
}
//show array
cout << "show array" << endl;
cout << "0 1 2 3 4 5 6 7 8 9" << endl;
for(i=0;i<10;i++){
cout << nums[i] << " ";
}
cout << endl;
//show numbers
cout << "show numbers" << endl;
for(i=0;i<10;i++){
randNum[nums[i]]=i; //get rand nums to randNum[]
}
for(i=0;i<10;i++){
cout << randNum[i] << " "; //output numbers
}
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
//亂數產生器-引入亂數表充當種子
int getRandom(int min,int max){
int n,v,seed[]={
29280,39655,18902,92531,90374, 7109,26627,59587,84340,98351,
20123,82082,55477,22059,43168,12903,13436,25523,21090,73449,
66405,35287,33248,67657, 7702, 1474,66068, 1125,59258,30138,
97299,83419,13069,17826,76984,48906,10567,17829, 723,46700,
83923,92076,98880,33942,46841,58731,36513,16681,88722,61984,
11258,92175,94894,97606,11134,51941,43733, 514, 6694,27706
};
n=(time(0)+clock())%60;
v=seed[n]+clock();
srand(v);
return (min + rand()%(max-min+1));
}
沒有留言:
張貼留言
請提供您的寶貴意見 ;-)