作者Stanauin (希臘行)
看板C_and_CPP
標題Re: [問題] 使用亂數產生一組樂透號碼
時間Wed Dec 7 20:03:45 2005
#include <iostream>
#include <ctime>
using namespace std;
class lottery
{
public:
lottery( unsigned int _all = 49, // 預設49個數
unsigned int _pick = 6 ); // 1次抽6個號碼
virtual ~lottery();
void setall(unsigned int _all); // 設置樂透總個數
void setpick(unsigned int _pick); // 設置挑選個數
void draw(unsigned int group = 1); // 抽號碼(group: 抽幾次)
protected:
void initall(); // 初始化全部樂透號碼
void shuffle(); // 隨機掉換
private:
unsigned int all; // 總個數
unsigned int pick; // 抽取數
int* number; // 全部的樂透號碼
};
lottery::lottery( unsigned int _all, unsigned int _pick )
{
all = _all;
pick = _pick;
number = NULL;
initall();
srand(time(NULL));
}
lottery::~lottery()
{
if( number )
delete [] number;
}
void lottery::shuffle()
{
unsigned i,j,n;
for( i=0; i<all; ++i )
{
n = number[i];
j = rand()%all;
number[i] = number[j];
number[j] = n;
}
}
void lottery::setall( unsigned int _all )
{
if( all != _all )
{
all = _all;
initall();
}
}
void lottery::setpick( unsigned int _pick )
{
if( pick != _pick )
pick = _pick;
}
void lottery::initall()
{
if( number )
delete [] number;
number = new int[all];
for( unsigned int i=0; i<all; ++i )
number[i] = i+1;
}
void lottery::draw(unsigned int group)
{
for( unsigned int i=0; i<group; ++i )
{
shuffle();
cout << "group " << i+1 << ": ";
for( unsigned int j=0; j<pick; ++j )
cout << number[j] << ' ';
cout << endl;
}
}
int main()
{
// 測試 lottery class: 使用預設值
lottery lot;
lot.draw();
// 測試 set 函式: 100個抽8個,抽5組
lot.setall( 100 );
lot.setpick( 8 );
lot.draw(5);
return 0;
};
--
賺一下批幣
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.68.76.233
→ gyb997:rand()是偽隨機函數,看高德納的計算機設計藝術2 12/07 23:10
推 gdgy:喔?能不能透露一下,沒聽說過耶 12/07 23:27