Java - Math, Random 이용한 로또 생성기 코드

Math, Random 관련 문제 풀어보기


로또 번호 생성기

  • 로또 번호 1 ~ 45 사이 숫자 6개 뽑는다.
  • 뽑은 숫자는 중복되어서는 안된다.
  • 매 실행마다 결과는 달라져야 한다.

Lotto.class

import java.util.Random;

public class Lotto {
    public final Random rand = new Random();
    public int r = rand.nextInt(45) + 1;
    public int[] numbers;

    public Lotto() {
        numbers = new int[6];
        for (int i = 0; i < numbers.length; i++) {
            randomize();
            numbers[i] = r;
        }
    }

    public int[] getNumber() {
        return numbers;
    }

    public void randomize() {
        while (isDupl(r)) {
            r = rand.nextInt(45) + 1;
        }
    }

    public boolean isDupl(int randPick) {
        for (int number : numbers) {
            if (number == randPick) {
                return true;
            }
        }
        return false;
    }
}

Main.class

public class Main {
    public static void main(String[] args) throws Exception {
        int[] numbers = new Lotto().getNumber();
        for (int n : numbers) {
            System.out.print(n + " ");
        }
    }
}

29 17 16 40 28 31

중복 방지 코드로 인해 길어보이지만 작동되는 것을 확인하였다.

while 문에서 유니크 값 체크해서 검증하는 것도 있다.

Lotto.class - while 문으로 사용

import java.util.Random;

public class Lotto {
    public final Random rand = new Random();
    public int r = rand.nextInt(45) + 1;
    public int[] numbers;

    public Lotto() {
        numbers = new int[6];
        int cnt = 0;
        while (cnt < 6) {
            int n = rand.nextInt(45) + 1;
            if (isUnique(n)) {
                numbers[cnt] = n;
                cnt++;
            }
        }
    }

    public int[] getNumber() {
        return numbers;
    }

    public boolean isUnique(int randPick) {
        for (int number : numbers) {
            if (number == randPick) {
                return false;
            }
        }
        return true;
    }
}

메인은 그대로 사용하여도 잘 동작한다.