mardi 4 octobre 2016

Efficient way to randomise numbers without duplications

I have used this code in order to randomise 1000000 numbers without duplication's. Here's what I have so far.

enter code here  protected void randomise() {
    int[] copy = new int[getArray().length];
    // used to indicate if elements have been used
    boolean[] used = new boolean[getArray().length];
    Arrays.fill(used,false);
    for (int index = 0; index < getArray().length; index++) {
        int randomIndex;
        do {
            randomIndex = getRandomIndex();
        } while (used[randomIndex]);
        copy[index] = getArray()[randomIndex];
        used[randomIndex] = true;
    }
    for (int index = 0; index < getArray().length; index++) {
        getArray()[index] = copy[index];
        //Checks if elements in array have already been used
    }
}

public static void main(String[] args) {
    RandomListing count = new SimpleRandomListing(1000000);
    //Will choose 1000000 random numbers
    System.out.println(Arrays.toString(count.getArray()));
}

This method is too slow can you let me know how this can be done more efficiently. I appreciate all replies. Regards,




Aucun commentaire:

Enregistrer un commentaire