How to shuffle array java

Java Shuffle Array shuffle()

Java collections framework comes with two classes Collections and Arrays (from java.util) to operate on the elements of collection classes (data structures) and arrays. To shuffle the elements of a data structure, the Collections class includes a method shuffle() but Arrays class does not come with one.

To shuffle the elements of an array, we must write our own algorithm or other way is convert the array elements into a collections class and then apply shuffle() method. Following programs uses both with different styles.

Following is the method signature of shuffle() method as defined in Collections class (not Array class).

  • static void shuffle(List list1): Shuffles the existing elements of list1 randomly. For repeated execution of the method, elements with different order are obtained.

Following program shuffles the elements, but here we write the code ourselves like in C/C++.

import java.util.*; // for Arrays and Random public class Demo < public static void main(String args[]) < Random rand = new Random(); int marks[] = new int[10]; for(int i = 0; i < 10; i++) < marks[i] = i; >System.out.println("Original array: " + Arrays.toString(marks)); // to shuffle the elements the C style for(int i = 0; i < 10; i++) < int someInt = rand.nextInt(marks.length); marks[i] = someInt; >System.out.println("Shuffled array: " + Arrays.toString(marks)); > >

Java Shuffle Array shuffle()

java.util. package comes with class Random used to generate random integers, doubles etc. with seed or without seed.

int someInt = rand.nextInt(marks.length);

The nextInt() method generates a random integer number. But passing marks.length as parameter generates random integers from 0 to marks.length.

Читайте также:  Sign in - Google Accounts

A marks integer array is created and assigned with 0 to 9 values in a for loop.

System.out.println("Original array: " + Arrays.toString(marks));

To print the elements of an array it takes a for loop. But there is shortcut in Java. Arrays.toString(marks) prints straightaway the marks elements.

Using the nextInt() method of Random class, each element of the array is assigned with random integer value. Executing the same for loop multiple times, different shuffling will be done. Observe the screen shot.

Let us go for Java Shuffle Array shuffle() and see how much code comes down and also simple.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo < public static void main(String args[]) < String numbers[] = < "one", "two", "three", "four", "five", "six" >; System.out.println("Original array: " + Arrays.toString(numbers)); // CONVERTING ARRAY TO LIST List myList = Arrays.asList(numbers); System.out.println("\nOriginal list: " + myList); Collections.shuffle(myList); System.out.println("First shuffled list: " + myList); Collections.shuffle(myList); System.out.println("Second shuffled list: " + myList); // CONVERTING LIST BACK TO ARRAY Object str[] = myList.toArray(); System.out.print("\nShuffled array: "); for(Object obj : str) < System.out.print(obj + " "); >> >

Java Shuffle Array shuffle()

A string array numbers is initialized and printed the values with toString() method of Arrays class.

List myList = Arrays.asList(numbers);

Now let us convert the array elements into a List. The asList() method of Array class returns a List object, here it is myList, containing the same elements of array numbers.

Now apply the shuffle() method of Collections class on myList. Now the List elements are shuffled.

Object str[] = myList.toArray(); System.out.print(«\nShuffled array: «); for(Object obj : str)

If required, you can get back the array from myList, as in the above code, with toArray() method..

Now you have seen how to convert array elements into List (with asList()) and List to array (with toArray()). It is how the Java designers made both arrays and collections classes interoperable. Separate programs are available to covert array to ArrayList and ArrayList to array.

Leave a Comment Cancel Reply

If you like our content, please show your love by liking our page on facebook

Источник

How to Shuffle an Array in Java

How to Shuffle an Array in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

1. Shuffle Array Elements using Collections Class

We can create a list from the array and then use the Collections class shuffle() method to shuffle its elements. Then convert the list to the original array.

package com.journaldev.examples; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ShuffleArray < public static void main(String[] args) < Integer[] intArray = < 1, 2, 3, 4, 5, 6, 7 >; List intList = Arrays.asList(intArray); Collections.shuffle(intList); intList.toArray(intArray); System.out.println(Arrays.toString(intArray)); > > 

Output: [1, 7, 5, 2, 3, 6, 4] Note that the Arrays.asList() works with an array of objects only. The concept of autoboxing doesn’t work with generics. So you can’t use this way to shuffle an array for primitives.

2. Shuffle Array using Random Class

We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.

package com.journaldev.examples; import java.util.Arrays; import java.util.Random; public class ShuffleArray < public static void main(String[] args) < int[] array = < 1, 2, 3, 4, 5, 6, 7 >; Random rand = new Random(); for (int i = 0; i < array.length; i++) < int randomIndexToSwap = rand.nextInt(array.length); int temp = array[randomIndexToSwap]; array[randomIndexToSwap] = array[i]; array[i] = temp; >System.out.println(Arrays.toString(array)); > > 

Output: [2, 4, 5, 1, 7, 3, 6]

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Shuffle an Array or a List — Algorithm in Java — Tutorial

1. Shuffle an array with the Collections framework

An array or an java.util.List data structure contains a sorted list of values. Shuffling an array or a list means that you are randomly re-arranging the content of that structure. Have you wondered how you could shuffle an array or a list without the collection framework? This article demonstrates how the shuffling works so that you can learn how the standard libraries might do this.

If you are only interested in using shuffling for the elements in a data structure, you can use Collections.shuffle(list) to shuffle a list with the standard Java library or Collections.shuffle(Arrays.asList(a)) to shuffle the entries in an array .

The approach works independent of the content of the array or the list.

The shuffle is random as the algorithm by selecting uniformly an element which has not been selected. For example if the element at position 2 is selected it can be exchanged with all elements at position 2 until position n-1 (as the list /array has 0 — n-1 positions).

2. Implementation in Java

Create a Java project «de.vogella.algorithms.shuffle». Create the following program for sorting arrays.

package de.vogella.algorithms.shuffle; import java.util.Random; public class ShuffleArray  public static void shuffleArray(int[] a)  int n = a.length; Random random = new Random(); random.nextInt(); for (int i = 0; i  n; i++)  int change = i + random.nextInt(n - i); swap(a, i, change); > > private static void swap(int[] a, int i, int change)  int helper = a[i]; a[i] = a[change]; a[change] = helper; > public static void main(String[] args)  int[] a = new int[]  1, 2, 3, 4, 5, 6, 7 >; shuffleArray(a); for (int i : a)  System.out.println(i); > > >

Create the following program for sorting list.

package de.vogella.algorithms.shuffle; import java.util.ArrayList; import java.util.List; import java.util.Random; public class ShuffleList  public static void shuffleList(ListInteger> a)  int n = a.size(); Random random = new Random(); random.nextInt(); for (int i = 0; i  n; i++)  int change = i + random.nextInt(n - i); swap(a, i, change); > > private static void swap(ListInteger> a, int i, int change)  int helper = a.get(i); a.set(i, a.get(change)); a.set(change, helper); > public static void main(String[] args)  ListInteger> list = new ArrayListInteger>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); list.add(7); shuffleList(list); for (int i : list)  System.out.println(i); > > >

Why does this shuffle all values randomly? The value at position 0 is exchanged with a randomly selected value (including the original value at position 0). This means that after the first loop, position 0 has a random value with an equal likelihood of any value. We continue this with position 1 but we do not need to consider position 0 again as this position already has a random value assigned. After the loop it is equally likely that each value is at any position.

Источник

Shuffle Array in Java

Shuffle Array in Java

  1. Use the random() Method to Shuffle an Array in Java
  2. Use the shuffle() Method to Shuffle an Array in Java

An array is one of the fundamental data structures in Java. Java is equipped with many functions and methods to process and work on arrays.

This tutorial demonstrates how to shuffle an array in Java.

Use the random() Method to Shuffle an Array in Java

We can use the Fisher-Yates shuffle array method to shuffle a given array randomly. This method aims to start from the last element of a given array and keep swapping it with a randomly selected element in the array.

We use the Random() function from the random class to randomly pick the indexes of an array. We will be importing two classes, Random and Arrays , from the java.util library.

import java.util.Random; import java.util.Arrays; public class ShuffleExample    static void rand( int array[], int a)    // Creating object for Random class  Random rd = new Random();   // Starting from the last element and swapping one by one.  for (int i = a-1; i > 0; i--)    // Pick a random index from 0 to i  int j = rd.nextInt(i+1);   // Swap array[i] with the element at random index  int temp = array[i];  array[i] = array[j];  array[j] = temp;  >  // Printing the random generated array  System.out.println(Arrays.toString(array));  >   public static void main(String[] args)     int[] ar = 1, 2, 3, 4, 5, 6, 7, 8>;  int b = ar.length;  rand (ar, b);  > > 

Use the shuffle() Method to Shuffle an Array in Java

The shuffle() function of the Collection class takes a list given by the user and shuffles it randomly. This function is easy to use and takes lesser time than the previous method. Also, it reduces the line of codes for us.

We take an array and first convert it into a list. Then, we use the shuffle() function to shuffle this list. Finally, we change this list back to an array and print it.

import java.util.*; public class ShuffleExample2  public static void main(String[] args)  Integer[] array=1,3,5,7,9>;  ListInteger> list =Arrays.asList(array);   Collections.shuffle(list);  list.toArray(array);  System.out.println(Arrays.toString(array));  > > 

In the above array, we can see our shuffled array. It returns a new shuffled array every time.

Related Article — Java Array

Copyright © 2023. All right reserved

Источник

Оцените статью