C_C++

(C언어) 로또 번호 생성: 중복되지 않은 수

enjoy-country-life 2022. 10. 2. 14:51
반응형

난수 발생은 프로그램에서 자주 사용되고 있습니다.
C언어의 난수는 rand() 함수를 이용하며, rand() 함수는 0 ~ 32767까지의 난수를 생성합니다.

rand();   // 0 ~ 32767까지의 난수 생성
rand() % 100;   // 0 ~ 99까지의 난수 생성
rand() % 100 + 1;   // 1 ~ 100까지의 난수 생성

 
실행할 떄마다 매번 다른 수를 생성하기 위해서는 srand 함수로 초기화를 해야 합니다.

#include <stdlib.h> 
#include <time.h>

srand((unsigned)time(NULL));

 

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void sort(int arr[], int n)
{
	int i, k, temp;
	for (i = 0; i < n - 1; i++)
	{
		for (k = 0; k < n - 1; k++)
		{
			if (arr[k] > arr[k + 1])   // 오름차순 정렬 
			{
				temp = arr[k];
				arr[k] = arr[k + 1];
				arr[k + 1] = temp;
			}
		}
	}
}

int main()
{
	int lotto[6] = { 0, };
	int i = 0, n = 0;

	// 매번 다른 수를 생성하도록 초기화
	srand((unsigned)time(NULL));
	while (1)
	{
		int r = rand() % 45 + 1; // 1~45 사이의 랜덤 수 생성, 중복 가능

		// 이미 생성된 번호인지(중복수) 체크
		for (i = 0; i < n; i++)
			if (lotto[i] == r) break;
		if (n == i) lotto[n++] = r; // 중복수가 아닐때에만 n위치에 수를 기억
		if (n >= 6) break; // 랜덤 수 6개가 생성되었으면 무한 반복을 벗어남
	}

	// 오름차순 정렬(버블정렬)
	sort(lotto, 6);

	// 생성된 번호 출력
	for (i = 0; i < 6; i++)
		printf("%d ", lotto[i]);
	printf("\n");

	return 0;
}

 

 

 

 

728x90
반응형