[問題] 亂數不重複
最近看到別人在討論這個問題,我自己想一個方法來實作產生52個亂數不重複
想法如下:
1.將陣列依序初始化1~52
2.隨機挑一個位置,將該位置所存的數字與最後一個位置交換
交換後的位置即是已確定的第一個亂數(也就是完成選擇的會由後端插入)
並將array最後一個位置往前移(ex:第一次位置52交換,第二次與位置51交換)
3.回Step 2
4.直到產生52個不同亂數為止
結果:
產生的亂數不會有重複
但發現了一個現象,我額外在加入程式碼判斷某一數字在52個位置內,
各出現幾次,發現數字好像有群聚現象,
例如第一次產生52亂數不同復,號碼1在位置20
接下來在總共100次產生52亂數不重複(其中不再進行各個位置初始化),號碼1再度出現
在位置20至少會有好幾次
也就是號碼該位置出現過一次,未來可能再度出現,
假如應用在撲克牌,甲方假設取得大老二,未來多次玩牌再度取得機率很高
程式碼如下:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#define SIZE 52
using namespace std;
void Init_poker(short int poker [] , int size ) //初始化
{
for(int i = 1 ; i < SIZE+1 ; ++ i )
poker[i-1] = i;
}
void Print_poker(short int poker [],int size)//顯示內容
{
for(int i = 0 ; i < SIZE ; ++ i )
cout << "porker[" << i << "]=" << poker[i] << endl;
}
void Swap(short int * x ,short int * y )
{
short int temp ;
temp = *x;
*x = *y;
*y = temp ;
}
void Shuffle_poker(short int poker [] , int size )
{
short int random_number;
short int current_poker_size = SIZE;
//初始亂數表
srand(time(NULL));
for(int i = 0 ; i < SIZE ; ++i ){
random_number = rand()% current_poker_size ; // 亂數挑選位置 0~51
//cout << "選到" <<random_number << endl;
//挑中位置與目前poker array最後一個位置交換,則最後位置即挑選完成數字
Swap(&poker[random_number],&poker[current_poker_size - 1]);
--current_poker_size;
//print_array(poker,SIZE);
}
}
int main()
{
short int poker[SIZE] ;
//初始1~52
Init_poker(poker,SIZE);
// system("PAUSE");
srand(time(NULL));
int count[SIZE]={0} ;
int i,j;
for ( i = 0 ; i < 100 ; i++){ //測試52次洗牌,是否夠亂
//Init_poker(poker,SIZE); //第二次洗牌不初始化
Shuffle_poker(poker,SIZE);
//Print_poker(poker,SIZE);
//system("PAUSE");
for( j =0 ; j < SIZE ; j++) //掃描1號數字在各個位置出現次數
if(poker[j] == 1) //統計1
count[j]++;
}
//統計1號在各個位置出現次數
for( j =0 ; j < SIZE ; j++){
cout << "poker["<< j<<"]=" << count[j]<<"次" << endl;
}
system("pause");
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 125.229.169.189
→
05/23 16:12, , 1F
05/23 16:12, 1F
→
05/23 16:25, , 2F
05/23 16:25, 2F
推
05/23 16:27, , 3F
05/23 16:27, 3F
→
05/23 17:02, , 4F
05/23 17:02, 4F
→
05/23 17:02, , 5F
05/23 17:02, 5F
推
05/23 17:04, , 6F
05/23 17:04, 6F
→
05/23 17:05, , 7F
05/23 17:05, 7F
討論串 (同標題文章)