Java Array Permute permute(T[] values)

Here you can find the source of permute(T[] values)

Description

"Randomly" permute an array in place.

License

Open Source License

Declaration

public static <T> T[] permute(T[] values) 

Method Source Code

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

import java.util.Random;

public class Main {
    /**//from  w w w . j  a va 2 s . c om
     * A random number generator for use in permutations and such.
     */
    static Random generator = new Random();

    /**
     * "Randomly" permute an array in place.
     */
    public static <T> T[] permute(T[] values) {
        for (int i = 0; i < values.length; i++) {
            swap(values, i, generator.nextInt(values.length));
        } // for
        return values;
    }

    /**
     * Swap two elements in an array.
     *
     * @param values, the array
     * @param i, one of the indices
     * @param j, another index
     * @pre 0 <= i,j < values.length
     * @pre a = values[i]
     * @pre b = values[j]
     * @post values[i] = b
     * @post values[j] = a
     */
    public static <T> void swap(T[] values, int i, int j) {
        T tmp = values[i];
        values[i] = values[j];
        values[j] = tmp;
    }
}

Related

  1. permute(int[] elements, int i, int j)
  2. permute(int[] in, int[] idx)
  3. permute(int[] p, Object[] data, boolean clone)
  4. permute(String str, int startIndex, int endIndex)
  5. permute(T[] array)
  6. permuteArray(int[] array, Integer[] permutation)
  7. permuteCols(double[][] ary, int[] idx)
  8. permuteList(List inList)
  9. permuteRows(double[][] ary, int[] idx)