vendredi 16 août 2019

Effective algorithm to random 4 integers less than a 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++) {

        // 1-max
        while (true) {
            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;
}

The algorithm is working fine. I guest there is a better algorithm for this problem, especially to a very big max number. Thank you!




Aucun commentaire:

Enregistrer un commentaire