Java

java 로또 번호 6개 (중복 없이)

녹녹1 2023. 8. 22. 18:53

문제

1부터 45 사이의 난수 6개를 추출하여 다음 형식으로 출력한다. 단, 6개 숫자는 중복을 허용하지 않는다.
[ 출력형식 ] 오늘의 로또 번호 - x, x, x, x, x, x

여기서 중복을 제거하는 것이 어려웠다.

 

초반에 i랑 i+1만 비교를 해서 자꾸 1, 3, 5, 10, 14, 1 이런식으로 중복이 나왔었다.

public class LottoMachine {
	public static void main(String[] args) {
		int[] lotto = new int[6];
		for (int i = 0; i < lotto.length; i++) {
			lotto[i] = (int) (Math.random() * 45) + 1;
			for (int j = 0; j < i; j++) {
				if (lotto[i] == lotto[j]) {
					i--;
					break;
				}
			}
		}
		System.out.print("오늘의 로또 번호 - ");
		for (int i = 0; i < lotto.length; i++) {
			System.out.printf("%d%s", lotto[i], (i != lotto.length - 1) ? "," : "");
		}
	}
}

 

중복을 없애려면 랜덤 숫자와 배열에 있는 모든 수를 다 비교해야 했다. 

그러려면 다시 반복문을 사용해서 검사를 하고 만약 중복 숫자가 있을 경우 i를 감소시켜서 다시 랜덤 숫자를 뽑으면 된다.

 

아래는 다른 분의 풀이 코드이다.

public class LottoMachine1 {
	public static void main(String[] args) {
		int[] lotto = new int[6];
		int idx = 0, ran;
		boolean flag;
		while (idx < lotto.length) {
			ran = (int) (Math.random() * 45) + 1;
			flag = true;
			for (int i = 0; i < idx; i++) {
				if (lotto[i] == ran) {
					flag = false;
					break;
				}
			}
			if (flag) {
				lotto[idx] = ran;
				idx++;
			}
		}
		System.out.print("오늘의 로또 번호 - ");
		for (int i = 0; i < lotto.length; i++) {
			System.out.printf("%d%s", lotto[i], (i != lotto.length - 1) ? "," : "");
		}
	}
}

이런식으로 while문을 사용해서 동일한 숫자가 있는지 검사를 먼저 한 뒤 없으면 lotto안에 저장하는 식으로 푸신 분도 있었다.