Java Array Permute permutation(int n)

Here you can find the source of permutation(int n)

Description

Generates a random permutation of the numbers {0, ..., n-1}

License

Open Source License

Parameter

Parameter Description
n the length of the set of numbers to permute

Return

a random permutation of the numbers {0, ..., n-1}

Declaration

public static int[] permutation(int n) 

Method Source Code

//package com.java2s;
/** A collection of mathematical utility functions.
 * <p>/*from  w ww  .ja v  a 2  s  .  co m*/
 * Copyright (c) 2008 Eric Eaton
 * <p>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * <p>
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 * @author Eric Eaton (EricEaton@umbc.edu) <br>
 *         University of Maryland Baltimore County
 *
 * @version 0.1
 *
 */

import java.util.Arrays;

import java.util.Collections;

import java.util.Random;

public class Main {
    static Random randGenerator = new Random(System.currentTimeMillis());

    /** Generates a random permutation of the numbers {0, ..., n-1}
     * @param n the length of the set of numbers to permute
     * @return a random permutation of the numbers {0, ..., n-1}
     */
    public static int[] permutation(int n) {
        return permutation(n, getRandomGenerator());
    }

    /** Generates a random permutation of the numbers {0, ..., n-1}
     * @param n the length of the set of numbers to permute
     * @param rand the random number generator
     * @return a random permutation of the numbers {0, ..., n-1}
     */
    public static int[] permutation(int n, Random rand) {
        int[] values = new int[n];
        for (int i = 0; i < n; i++) {
            values[i] = i;
        }
        Collections.shuffle(Arrays.asList(values));
        return values;
    }

    /** Retrieves the initialized random number generator.  Use of this
     * rand generator allows an entire program to use a single rand generator.
     * @return the initialized random number generator.
     */
    public static Random getRandomGenerator() {
        return randGenerator;
    }
}

Related

  1. permutation(final int start, final int end)
  2. permute(int k, Object[] os)
  3. permute(int[] elements, int i, int j)
  4. permute(int[] in, int[] idx)
  5. permute(int[] p, Object[] data, boolean clone)