특정 범위의 정수타입 난수를 어떻게 생성하나요?

조회수 4305회

자바를 사용해서 특정 범위의 int 타입의 난수를 생성하고자 합니다.

예를 들어:

최소값 5, 최대값 10으로 5에서 10까지의 범위의 난수를 생성하고자 합니다.

자바에서 Math 클래스의 random() 메소드는 0.0이상 1.0 미만의 double 타입의 난수를 생성합니다. Random 클래스의 nextInt(int n) 메소드는 0이상 n 미만의 int 타입의 값을 생성합니다. 그러나 저는 두 수 사이의 정수 난수를 생성해주는 메소드는 찾을 수가 없습니다.

그래서 다음과 같시 시도해봤습니다. 그러나 여전히 문제들은 남아있습니다.

해결 1:

randomNum = minimum + (int)(Math.random() * maximum); 

문제:

randomNummaximum보다 클 수 있습니다.

해결 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

문제:

randomNum'은minimum`보다 작을 수 있습니다.

이 문제를 어떻게 해결할 수 있을까요?

제가 인터넷 검색해서 찾아본 내용들입니다.

그러나 문제를 해결할 수 없었습니다. 도와주세요.

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    자바 1.7 버전 이전의 표준적인 방법은 다음과 같습니다:

    import java.util.Random;
    
    /**
     * Returns a pseudo-random number between min and max, inclusive.
     * The difference between min and max can be at most
     * <code>Integer.MAX_VALUE - 1</code>.
     *
     * @param min Minimum value
     * @param max Maximum value.  Must be greater than min.
     * @return Integer between min and max, inclusive.
     * @see java.util.Random#nextInt(int)
     */
    public static int randInt(int min, int max) {
    
        // NOTE: This will (intentionally) not run as written so that folks
        // copy-pasting have to think about how to initialize their
        // Random instance.  Initialization of the Random instance is outside
        // the main scope of the question, but some decent options are to have
        // a field that is initialized once and then re-used as needed or to
        // use ThreadLocalRandom (if using at least Java 1.7).
        Random rand;
    
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;
    
        return randomNum;
    }
    

    관련 JavaDoc을 확인해보세요. 실무에서는 java.util.Random 클래스를 java.lang.Math.random() 메소드보다 종종 더 선호하는 경향이 있습니다.

    특히, 작업을 수행하는 표준 라이브러리 내의 간단한 API가 있을 때 정수를 생성하는 기능을 다시 구현할 필요가 없습니다.

    자바 1.7 버전 이후에는 다음과 같은 메소드를 사용해서 명확히 시작값을 설정할 필요 없이 쉽게 원하는 값을 얻을 수 있습니다.

    import java.util.concurrent.ThreadLocalRandom;
    
    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    ThreadLocalRandom.current().nextInt(min, max + 1);
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)