lotto003.cpp
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <algorithm> // std::sort, std::find, std::copy
#include <vector> // std::vector
void getRandomLottoWin(int *r) // 당첨번호+보너스번호(7수) 랜덤 생성
{
std::vector<int> vv; // vector vv 선언(중복검사, 정렬 등의 작업이 편하다)
while(true) {
int temp = rand()%45 + 1; // 1~45 사이의 랜덤값 추출
if(std::find(vv.begin(), vv.end(), temp)==vv.end()) { // 벡터 vv 에 temp 값이 없다면
vv.push_back(temp); // 벡터 vv 에 temp 값을 추가
if(vv.size()==7) break; // 7수 모두를 얻었다면 while 루프를 빠져 나감
}
}
std::sort(vv.begin(), vv.begin()+6); // 정렬(보너스번호 빼고)
std::copy(vv.begin(), vv.end(), r); // 복사
}
void getRandomLotto(int *r) // 로또번호(6수) 랜덤 생성
{
std::vector<int> vv; // vector vv 선언(중복검사, 정렬 등의 작업이 편하다)
while(true) {
int temp = rand()%45 + 1; // 1~45 사이의 랜덤값 추출
if(std::find(vv.begin(), vv.end(), temp)==vv.end()) { // 벡터 vv 에 temp 값이 없다면
vv.push_back(temp); // 벡터 vv 에 temp 값을 추가
if(vv.size()==6) break; // 6수 모두를 얻었다면 while 루프를 빠져 나감
}
}
std::sort(vv.begin(), vv.end()); // 정렬
std::copy(vv.begin(), vv.end(), r); // 복사
}
int main(int argc, char *argv[])
{
srand((unsigned)time(NULL));
int r1[7]; // 랜덤으로 생성된 로또번호+보너스번호 를 저장할 배열
for(int i=0; i<10; i++) {
getRandomLottoWin(r1);
printf("%02d,%02d,%02d,%02d,%02d,%02d / %02d\n", r1[0],r1[1],r1[2],r1[3],r1[4],r1[5],r1[6]);
}
printf("\n");
int r2[6]; // 랜덤으로 생성된 로또번호를 저장할 배열
for(int i=0; i<10; i++) {
getRandomLotto(r2);
printf("%02d,%02d,%02d,%02d,%02d,%02d\n", r2[0],r2[1],r2[2],r2[3],r2[4],r2[5]);
}
getchar();
return 0;
}
랜덤으로 로또 번호를 생성하는 함수입니다.
getRandomLottoWin() 은 보너스볼까지 총 7수가 랜덤 생성되며
getRandomLotto() 은 총 6수가 랜덤 생성됩니다.
C 표준 랜덤함수 rand() 의 분포가 좋지 않다고는 하지만,
1~45 사이의 랜덤을 구하는 용도로는 큰 문제가 되지 않을것입니다.
(그래도 마음에 들지 않다면, 다른 랜덤 함수를 사용하면 되겠죠?)
'프로그래밍' 카테고리의 다른 글
로또번호 자동 생성 (응용편)(c/c++)(로또함수) (0) | 2014.08.04 |
---|---|
random, rand(), 큰수 랜덤, WELL 랜덤 (c/c++) (0) | 2014.08.04 |
순서번호로 로또 조합 알아내기 (c/c++)(로또함수) (0) | 2014.08.03 |
로또번호로 몇번째 조합인지 알아내기 (c/c++)(로또함수) (0) | 2014.08.03 |
로또 완전 조합 루프문 (c/c++)(로또함수) (0) | 2014.08.03 |