C언어 알고리즘 정리 및 실무 프로젝트

rand()를 이용한 로또 추출 알고리즘과 정렬 본문

C언어 알고리즘

rand()를 이용한 로또 추출 알고리즘과 정렬

C's everything! 2022. 4. 20. 16:52
반응형
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>	// rand(), srand()
#include <time.h>	// time()

void lotto_sort(int lotto[]);
int main() {

	int count = 0;		// 로또 번호 카운트
	int count_1;		// 구할 로또의 갯수
	int num[6];		// 원본 로또
	int cp[6] = { 0 };	// 비교할 로또

	srand((unsigned)time(NULL));

	printf("구할 로또의 갯수를 입력하세요 \n");
	scanf("%d", &count_1);

	for (int i = 0; i < count_1; i++) {

		for (int j = 0; j < 6; j++) {
			num[j] = 1+rand() % 45;
			
			if (num[j] == cp[0] || num[j] == cp[1] || num[j] == cp[2] || num[j] == cp[3] || num[j] == cp[4] || num[j] == cp[5]) {
				// (j+1)번째 원본 로또의 요소와 6개의 요소를 모두 비교
				// 같은게 하나라도 있다면 j의 값을 감소시켜서 num[j]에 새로운 난수 값을 할당
			
				j--;
			}
			else
			{
				cp[j] = num[j];
			}
		}
		count++;
		printf("%d번째 로또 배열: ",count);
		lotto_sort(num);
		for (int i = 0; i < 6; i++) {
			cp[i] = 0;
		}
	}




	return 0;
}

void lotto_sort(int lotto[6]) {		//  로또를 오름차순 정렬
	int i, j, temp;

	for(i = 0; i < 5; i++) {
		for (j = i + 1; j < 6; j++) {
			if (lotto[i] < lotto[j]) {
				temp = lotto[i];
				lotto[i] = lotto[j];
				lotto[j] = temp;
			}
		}
	}

	
	for (i = 0; i < 6; i++) {
		printf("%d ", lotto[i]);
	}
	printf("\n");
	
}
반응형
Comments