Java에서 랜덤 숫자 생성하기

랜덤 숫자를 생성하는 것은 프로그래밍에서 매우 일반적인 작업입니다. Java에서는 다양한 방법으로 램덤 숫자를 생성할 수 있습니다. 아래는 세 가지 주요 방법에 대한 설명과 코드 예제입니다.

1. Math.random() 활용

Math.random() 메서드는 0.0 이상 1.0 미만의 double 값을 반환합니다. 이를 통해 특정 범위 내의 정수형 랜덤 숫자를 쉽게 얻을 수 있습니다.


public void generateRandomWithMath(int min, int max) {
    double randomDouble = Math.random();
    int range = max - min + 1;
    int randomNumber = (int)(randomDouble * range) + min;
    System.out.println("생성된 랜덤 숫자: " + randomNumber);
}

2. System.currentTimeMillis() 활용

System.currentTimeMillis()는 현재 시간을 밀리초 단위로 반환하며, 이를 기반으로 랜덤한 값을 만들 수 있습니다. 주로 모듈러 연산을 사용하여 범위를 제한합니다.


public void generateRandomWithTime(int min, int max) {
    long currentTime = System.currentTimeMillis();
    int randomNumber = (int)(currentTime % (max - min + 1)) + min;
    System.out.println("생성된 랜덤 숫자: " + randomNumber);
}

3. Random 클래스 활용

Random 클래스는 더 다양한 랜덤 값 생성 메서드들을 제공합니다. 이를 통해 정수, 실수 등의 랜덤 값을 쉽게 얻을 수 있습니다.


import java.util.Random;

public void generateRandomWithRandomClass(int min, int max) {
    Random rand = new Random();
    int randomNumber = rand.nextInt((max - min) + 1) + min;
    System.out.println("생성된 랜덤 숫자: " + randomNumber);
}

N개의 고유 랜덤 숫자 생성

여러 개의 고유한 랜덤 숫자를 생성해야 하는 경우도 많습니다. 이를 위한 몇 가지 방법을 소개합니다.

1. 중복 체크를 통한 생성

중복되지 않는 숫자를 배열에 저장하면서 생성하는 방식입니다.


public int[] generateUniqueRandomNumbers(int min, int max, int count) {
    if (count > (max - min + 1) || min > max) return null;
    int[] result = new int[count];
    int index = 0;
    while (index < count) {
        int num = (int)(Math.random() * (max - min + 1)) + min;
        boolean isDuplicate = false;
        for (int j = 0; j < index; j++) {
            if (result[j] == num) {
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate) {
            result[index++] = num;
        }
    }
    return result;
}

2. HashSet을 활용한 중복 제거

HashSet은 중복을 허용하지 않는 자료 구조이므로 이를 활용하면 간단히 고유한 랜덤 숫자를 생성할 수 있습니다.


import java.util.HashSet;

public HashSet<Integer> generateUniqueRandomWithSet(int min, int max, int count) {
    if (count > (max - min + 1) || min > max) return null;
    HashSet<Integer> set = new HashSet<>();
    while (set.size() < count) {
        int num = (int)(Math.random() * (max - min + 1)) + min;
        set.add(num);
    }
    return set;
}

3. 남은 후보군 제거 방식

처음부터 모든 가능한 숫자를 배열로 준비하고, 랜덤하게 선택하면서 선택된 숫자를 제거해 나가는 방식입니다.


import java.util.Random;

public int[] generateUniqueRandomByRemovingCandidates(int min, int max, int count) {
    if (count > (max - min + 1) || min > max) return null;
    int length = max - min + 1;
    int[] candidates = new int[length];
    for (int i = 0; i < length; i++) {
        candidates[i] = min + i;
    }

    int[] result = new int[count];
    Random rand = new Random();
    for (int i = 0; i < count; i++) {
        int idx = rand.nextInt(length - i);
        result[i] = candidates[idx];
        candidates[idx] = candidates[length - i - 1];
    }
    return result;
}

태그: java Random algorithm

7월 30일 19:30에 게시됨