Java Program to create an array with randomly shuffled numbers in a given range

Java 8Object Oriented ProgrammingProgramming

For randomly shuffled numbers, let us create an integer list and add some numbers −

List < Integer > list = new ArrayList < Integer > ();
list.add(10);
list.add(50);
list.add(100);
list.add(150);
list.add(200);

Now, shuffle the elements for random values −

Collections.shuffle(list);

Create an int array with the same number of elements in the above list −

intlen = list.size();
int[] res = newint[len];

Set the shuffled values in the new array −

for (inti = 0; i < len; i++) {
   res[i] = list.get(i);
}

Example

 Live Demo

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) {
      List<Integer>list = new ArrayList<Integer>();
      list.add(10);
      list.add(50);
      list.add(100);
      list.add(150);
      list.add(200);
      list.add(350);
      list.add(500);
      list.add(800);
      list.add(1000);
      Collections.shuffle(list);
      int len = list.size();
      int[] res = new int[len];
      for (int i = 0; i < len; i++) {
         res[i] = list.get(i);
      }
      System.out.println("Randomly shuffled array elements = "+Arrays.toString(res));
   }
}

Output

Randomly shuffled array elements = [10, 200, 1000, 350, 100, 50, 500, 800, 150]
raja
Published on 23-Apr-2019 12:55:18
Advertisements