- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to create an array with randomly shuffled numbers in a given range
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
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]
Advertisements