LHA
LHA

Reputation: 9655

Effective algorithm to random 4 unique integers less than a big max such as 100_000

Here is my try:

public static void main(String[] args) {
    // Max 100_000
    System.out.println(Arrays.toString(randomFour(100_000)));
}

public static int[] randomFour(int max) {
    Random r = new Random();
    int[] four = new int[4];

    for (int i = 0; i < 4; i++) {

        while (true) {
            // Random from 1 to max
            four[i] = 1 + (int) (r.nextFloat() * max);

            boolean dup = false; // check j: 0 -> i-1
            for (int j = 0; j < i; j++) {
                if (four[j] == four[i]) {
                    dup = true;
                    break;
                }
            }
            if (dup == false) {
                break;
            }
        }
    }
    return four;
}

This implementation is working fine. Is there a better algorithm for this problem (both time & memory consuming), especially to a very big max number? Thanks!

Upvotes: 1

Views: 79

Answers (1)

JB Nizet
JB Nizet

Reputation: 692081

If I understand correctly, you want to have an array of 4 distinct random integers between 1 and 100_000 (inclusive).

Here's a concise end expressive way of doing that

int[] four = ThreadLocalRandom.current()
                     .ints(1, 100_001) // 1 is inclusive, 100_001 is exclusive
                     .distinct()
                     .limit(4)
                     .toArray();

Upvotes: 6

Related Questions