How to randomize and shuffle array of numbers in Java?

Java 8Object Oriented ProgrammingProgramming

At first, create an integer array −

int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};

Now, create a Random class object −

Random rand = new Random();

Loop until the length of the array and shuffle the elements −

for (int i = 0; i < arr.length; ++i) {
   int index = rand.nextInt(arr.length - i);
   int tmp = arr[arr.length - 1 - i];
   arr[arr.length - 1 - i] = arr[index];
   arr[index] = tmp;
}

Example

 Live Demo

import java.util.Arrays;
import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};
      System.out.println("The integer array = "+Arrays.toString(arr));
      Random rand = new Random();
      for(int i = 0; i < arr.length; ++i) {
         int index = rand.nextInt(arr.length - i);
         int tmp = arr[arr.length - 1 - i];
         arr[arr.length - 1 - i] = arr[index];
         arr[index] = tmp;
      }
      System.out.println("Shuffle integer array = "+Arrays.toString(arr));
   }
}

Output

The integer array = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
Shuffle integer array = [160, 100, 20, 60, 140, 200, 120, 40, 80, 180]
raja
Published on 23-Apr-2019 12:57:14
Advertisements