samedi 2 avril 2016

Populate int[] with random numbers

I have made an quiz app which uses a int[] array to set the position of the answers. The array has to be filled with the numbers 0,1,2 and 3, but they have to be randomly placed ( and only occure once). The only way I managed to do it was like this:

public int[] castRanInt(){
    int ran_int[] = new int[4];
    Random random = new Random();
    boolean state = true;
    ran_int[0] = random.nextInt(4);
    while (state) {
        for (int r = 1; r < 4; r++) {
            ran_int[r] = random.nextInt(4);
        }
        state = false;
        for (int a = 0; a < 4; a++) {
            for (int b = 0; b < 4; b++) {
                if (a == b) {
                    continue;
                }
                if (ran_int[a] == ran_int[b]) {
                    state = true;
                }

            }
        }
    }
    return ran_int;
}

The only problem is that this often takes up to 100 runs in the while loop just to populate the array. Is there a simpler / faster way to do this?




Aucun commentaire:

Enregistrer un commentaire