Learn-dsa..in 30 days!



























CC-18 : Shuffle and Randomize array elements (use Fischer-Yates algorithm).

Description:

Given input integer array arr, shuffle the elements of the array and return array. Use Fisher-Yates algorithm to shuffle the array elements.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,4} One possible output is given below (output will be different every time you run the program):2,4,3,1
arr={-1,-2,-3,-4 } One possible output is -3,-1,-4,-2
arr={-3,-2,-1,0,1,2,3 } One possible output is 1,-2,0,-3,3,-1,2

Pseudocode:

The java method should accept following input parameters: arr (int array).
Iterate through arr using a for loop using loop variable idx:
Use java Random class object to generate a shuffled index between 0 and arr.length-1.
Swap the values between arr[idx] and arr[shuffleIdx].
When the above loop completes the array elements will be shuffled/randomized and we can return the array.

Code:

public int[] arrayShuffleRandomize(int[] arr) throws Exception{
	int temp=0;
	Random rGen=new Random();
	int shuffledIdx=0;
	for (int idx=0; idx< arr.length; idx++) {
		shuffledIdx=rGen.nextInt(0,arr.length);
		temp=arr[idx];
		arr[idx]=arr[shuffledIdx];
		arr[shuffledIdx]=temp;		
	}
	return arr;	
}

Click here to download and run code and test cases !