C,C++/개념 실습 프로그래밍
[c언어]중복없는 난수 생성하기 method_1
luckybee
2022. 9. 25. 20:23
728x90
반응형
일반적으로 난수를 생성하려면 time.h 헤더와 stdlib.h 헤더를 include 해줘야 한다.
#include<stdio.h>
#include<stdlib.h> //srand 함수를 사용하기 위해서
#include<time.h> //time 함수를 사용하기 위해서
int main()
{
int arr[16] = {}; //16개의 값을 담을 수 있는 배열 생성
srand((unsigned int)time(NULL)); //난수를 발생시키기 위해 난수 세팅
for (int i = 0; i < 15; i++){
arr[i]=rand() % 20; //0~19의 난수가 배열안에 대입
}
for (int i = 0; i < 15; i++){
printf("%d ", arr[i]); //출력
}
}
위와 같이 평범하게 난수를 발생시키면 위와 같이 중복 값이 들어온다. 그러면 이 중복 값을 들어오지 않게 하려면 어떻게 하면 될까?
아래 코드를 보자
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int arr[16] = {}; //배열 초기화
int temp,count=0; //난수를 대입할 tmep와 count 변수
bool flag = false; //플레그 변수
srand((unsigned int)time(NULL)); //난수 설정
for (int i = 0; i < 15; i++){
temp= rand() % 16; //0~15의 난수 발생
for (int j = 0; j < count&&i!=0; j++){ //i는 0이면 안된다.
if (temp == arr[j]){ //난수와 arr의 들어간 값 전부 탐색 만약 같은 숫자가 있으면
flag = true; //플레그 true
break; //반복문 탈출
}
}
if (flag){ //플레그에 들어왔으면
flag = false; //다시 플레그 false설정
i--; //반복문 i--
continue;
}
arr[i] = temp; //만약 위에 조건문들에 다 안들어왔으면 변수 대입
count++; //count++
}
for (int i = 0; i < 15; i++){ //출력 반복문
printf("%d ", arr[i]);
}
}
위와 같이 코드를 구성하면 실행화면은 0~15 사이의 숫자로 구성되어야 하고 중복은 없어야 한다.
위 사진처럼 중복 없는 난수의 값이 배열에 잘 들어갔다. 보기 불편하니 정렬 코드를 넣어서 제대로 한번 더 확인해보겠다.
제대로 들어간 것을 확인할 수 있다. 아래는 간단하게 선택 정렬까지 넣은 코드이다.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int arr[16] = {};
int temp,count=0;
bool flag = false;
srand((unsigned int)time(NULL));
for (int i = 0; i < 15; i++){
temp= rand() % 20;
for (int j = 0; j < count && i != 0; j++){
if (temp == arr[j]){
flag = true;
break;
}
}
if (flag){
flag = false;
i--;
continue;
}
arr[i] = temp;
count++;
}
int temp2;
for (int i = 0; i < 15; i++) {
for (int j = i; j < 15; j++) {
if (arr[i] > arr[j]) {
temp2 = arr[i];
arr[i] = arr[j];
arr[j] = temp2;
}
}
}
for (int i = 0; i < 15; i++){
printf("%d ", arr[i]);
}
}
난수의 값을 바꿔서 실행해봐도 중복은 없었다.
728x90
반응형