generates a random permutation of integers - Java java.lang

Java examples for java.lang:int

Description

generates a random permutation of integers

Demo Code


//package com.java2s;
import java.util.ArrayList;

public class Main {
    public static void main(String[] argv) throws Exception {
        int n = 2;
        System.out.println(randPerm(n));
    }/*from   w  w  w .j  a va2 s . co  m*/

    /**
     * generates a random permutation of integers
     * 
     * @param n  the number of integers you want in the permutation starting with 1
     * @return  an ArrayList containing your freshly baked permutation 
     */
    public static ArrayList<Integer> randPerm(int n) {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        for (int i = 1; i <= n; i++) {
            arrayList.add(i);
        }
        shuffle(arrayList);
        return arrayList;
    }

    /** 
     * randomly permutes all entries in an ArrayList
     * 
     * @param arrayList the ArrayList that you want to shuffle
     */
    public static <T extends Comparable<? super T>> void shuffle(
            ArrayList<T> arrayList) {
        for (int i = 0; i < arrayList.size(); i++) {
            swap(arrayList, i, (int) (Math.random() * arrayList.size()));
        }
    }

    /**
     * swaps two entries of an ArrayList
     * 
     * @param arrayList  the ArrayList whose entries you want to swap
     * @param yin  the index of the first swapped entry
     * @param yang  the index of the other swapped entry
     */
    public static <T extends Comparable<? super T>> void swap(
            ArrayList<T> arrayList, int yin, int yang) {
        T qi = arrayList.get(yin);
        arrayList.set(yin, arrayList.get(yang));
        arrayList.set(yang, qi);
    }
}

Related Tutorials