Friday, 24 May 2019

Shuffle the elements of array in Java


Approach 1: Using Fisher–Yates shuffle algorithm
//To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
     j random integer such that 0 ≤ j ≤ i
     exchange a[j] and a[i]

public static void shuffleArray(int[] arr) {
         int randomIndex;
         Random random = new Random();
         for (int i = arr.length - 1; i > 0; i--) {
                  randomIndex = random.nextInt(i + 1);

                  int temp = arr[randomIndex];
                  arr[randomIndex] = arr[i];
                  arr[i] = temp;

         }
}

App.java
package com.sample.app;

import java.io.IOException;
import java.util.Random;

public class App {

 public static void shuffleArray(int[] arr) {
  int randomIndex;
  Random random = new Random();
  for (int i = arr.length - 1; i > 0; i--) {
   randomIndex = random.nextInt(i + 1);

   int temp = arr[randomIndex];
   arr[randomIndex] = arr[i];
   arr[i] = temp;

  }
 }
 
 private static void printArray(int[] arr)
 {
  for(int ele : arr) {
   System.out.print(ele + " , ");
  }
  System.out.println();
 }
 public static void main(String args[]) throws IOException {
  int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
  
  printArray(arr);
  shuffleArray(arr);
  printArray(arr);
 }
}

Reference
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Approach 2: Using Collections.shuffle method
public static void shuffleArray(int[] arr) {
         List<Integer> list = new ArrayList<>();

         for (int data : arr) {
                  list.add(data);
         }

         Collections.shuffle(list);

         int i = 0;

         for (int data : list) {
                  arr[i] = data;
                  i++;
         }

}


App.java
package com.sample.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class App {

 public static void shuffleArray(int[] arr) {
  List<Integer> list = new ArrayList<>();

  for (int data : arr) {
   list.add(data);
  }

  Collections.shuffle(list);

  int i = 0;

  for (int data : list) {
   arr[i] = data;
   i++;
  }

 }

 private static void printArray(int[] arr) {
  for (int ele : arr) {
   System.out.print(ele + " , ");
  }
  System.out.println();
 }

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

  printArray(arr);
  shuffleArray(arr);
  printArray(arr);
 }
}

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


You may like

No comments:

Post a Comment