Wednesday 29 July 2015

Arrange elements of an array in random order

You can solve this problem by using Fisher–Yates shuffle algorithm. Go through following wiki link to know more about Fisher–Yates shuffle algorithm.

import java.util.Objects;
import java.util.Random;

public class ShuffleArray {

 private static int getRandomNumberInRange(int start, int end) {
  Random rand = new Random();
  int randomNum = rand.nextInt((end - start) + 1) + start;
  return randomNum;
 }

 public static void shuffleArray(int arr[]) {
  Objects.nonNull(arr);

  int length = arr.length - 1;

  if (length == 0)
   return;

  for (int i = length; i >= 0; i--) {
   int randomPositon = getRandomNumberInRange(0, i);

   /* Swap elements */
   int temp = arr[i];
   arr[i] = arr[randomPositon];
   arr[randomPositon] = temp;
  }
 }
}


public class ShuffleArrayTest {
 public static void printArray(int arr[]) {
  for (int i : arr)
   System.out.print(i + " ");
  System.out.println();
 }

 public static void main(String args[]) {
  int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

  for (int i = 0; i < 10; i++) {
   ShuffleArray.shuffleArray(arr);
   printArray(arr);
  }
 }
}


Sample Output
2 3 9 5 4 8 6 1 7 
3 2 1 4 9 8 7 6 5 
2 9 3 8 6 7 4 1 5 
4 6 5 3 8 7 1 9 2 
5 3 4 8 7 9 1 6 2 
3 7 1 4 6 9 2 8 5 
6 5 9 3 4 1 8 7 2 
3 1 6 2 7 8 5 4 9 
2 7 8 9 4 1 6 3 5 
7 5 3 9 6 2 8 4 1 



No comments:

Post a Comment