Java ThreadLocalRandom shuffle(T[] arr)

Here you can find the source of shuffle(T[] arr)

Description

shuffle

License

Open Source License

Declaration

public static <T> void shuffle(T[] arr) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static final Random RANDOM = ThreadLocalRandom.current();

    public static <T> void shuffle(T[] arr) {
        int n = arr.length;
        if (n <= 1) {
            return;
        }/*from   www .  j av a2  s  . c  om*/
        for (int i = n - 1; i > 0; --i) {
            swap(arr, i, randomInt(i));
        }
    }

    /**
     * Swap values in array
     *
     * @param arr array
     * @param i   index i
     * @param j   index j
     */
    private static <T> void swap(T[] arr, int i, int j) {
        T t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    /**
     * swap ints at given positions in array
     *
     * @param arr array
     * @param i   position
     * @param j   position
     */
    public static void swap(int[] arr, int i, int j) {
        arr[i] ^= arr[j];
        arr[j] ^= arr[i];
        arr[i] ^= arr[j];
    }

    /**
     * Return randomize integer that is bounded by given bound
     *
     * @param bound integer bound
     * @return randomize integer
     */
    public static int randomInt(int bound) {
        return RANDOM.nextInt(bound);
    }
}

Related

  1. randomString(List strings)
  2. randomStringArray(int arrayLength, int stringLength)
  3. randomWorld()
  4. randomWorld()
  5. shuffle(final T[] array)
  6. shuffle(T[] array)
  7. shuffleArray(int[] ar)
  8. timestampToMicros(final long timestampMillis)