Fisher yates Shuffle

时间:2017-05-09 17:55:12

标签: java shuffle

static void shuffle(int[] array) {
    int n = array.length;
    for (int i = 0; i < array.length; i++) {
        // Get a random index of the array past i.
        int random = i + (int) (Math.random() * (n - i));
        // Swap the random element with the present element.
        int randomElement = array[random];
        array[random] = array[i];
        array[i] = randomElement;
    }
}

public static void main(String[] args) {
     int[] values = { 1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13,14,15,16,17,18,19,20};

    // Shuffle integer array.
    shuffle(values);
    // Display elements in array.
    for (int value :values) {
        System.out.print(" " +value);
        //System.out.println(val);
    }
}

我想按名称更改值数组,例如deni,amir,cintia等 帮助,即时新手

1 个答案:

答案 0 :(得分:0)

I have succeeded in completing it :))


 static void shuffle(String[] array) {
    int n = array.length;
    for (int i = 0; i < array.length; i++) {
        // Get a random index of the array past i.
        int random = i + (int) (Math.random() * (n - i));
        // Swap the random element with the present element.
        String randomElement = array[random];
        array[random] = array[i];
        array[i] = randomElement;
    }
}