Tuesday, April 19, 2011

Shuffle an Array




package amazon;

import java.util.Arrays;

public class ShuffleArray {

/**
* http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
* http://www.careercup.com/question?id=8729811
*
* A functions inputs an array and gives out a shuffled version of the input array. The technique he described is to generate random value between 0 and n-1 and append the particular value from the input list to the output list. He wanted me to give a correct way of doing this.
*/
public static void main(String[] args) {
int[] srcArray = new int[] {1,2,3,4,5,6,7,8,9};
int src,dest,temp;

for(int i=0;i int rand = 0 + (int) (Math.random()*(srcArray.length-i));
src = srcArray[rand];
dest = srcArray[(srcArray.length-1)-i];
temp = src;
srcArray[rand]= dest;
srcArray[(srcArray.length-1)-i] = src;
}

System.out.println(Arrays.toString(srcArray));


}

}