ChooseLotto(int* numbers)가 실제로는 “배열의 시작 주소”를 받는다는 것을 설명할 수 있다.0 ~ count-1까지만 보면 되는지 설명할 수 있다.count - 1 - i가 무엇을 의미하는지 말로 설명할 수 있다.void Swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
핵심:
int&)를 쓰면 “원본”을 직접 바꿀 수 있습니다.void Sort(int* numbers, int count) {
if (numbers == nullptr || count <= 1)
return;
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - 1 - i; j++) {
if (numbers[j] > numbers[j + 1]) {
Swap(numbers[j], numbers[j + 1]);
}
}
}
}
count - 1 - i의 의미:i가 증가할수록 뒤쪽은 이미 정렬된 영역이므로, 비교 범위를 줄여도 됩니다.복잡도 감각:
void ChooseLotto(int* numbers) {
if (numbers == nullptr)
return;
int count = 0;
while (count != 6) {
int randValue = 1 + rand() % 45;
int i;
for (i = 0; i < count; i++) {
if (numbers[i] == randValue) break; // 중복 확인
}
if (i == count) { // 중복이 아닌 경우에만 저장
numbers[count] = randValue;
count++;
}
}
Sort(numbers, 6);
}
핵심 아이디어:
count는 “현재까지 채운 개수”입니다.numbers[count]에 넣고 count++.자주 하는 실수:
for (i = 0; i < 6; i++)로 돌려서 아직 채우지 않은 쓰레기 값까지 비교해버리기i < count여야 합니다.void Print(int* numbers, int count) {
if (numbers == nullptr || count <= 0)
return;
for (int i = 0; i < count; i++) {
std::cout << numbers[i] << ' ';
}
std::cout << '\n';
}
int main() {
srand((unsigned)time(0));
int lotto[6] = {};
ChooseLotto(lotto);
Print(lotto, 6);
return 0;
}
실행 결과 예시: 7 12 18 24 36 42 (중복 없음, 오름차순)
ChooseLotto(lotto)에서 lotto는 값이 전달될까, 주소가 전달될까?ChooseLotto의 중복 검사에서 왜 i < count까지만 보면 되는가?count - 1 - i가 “확정된 영역”을 의미하는 이유는?