Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to shuffle an array in Java

2 Answers

0 votes
import java.util.concurrent.ThreadLocalRandom;
import java.util.Random;

public class MyClass {
    static void shuffleArray(int[] arr) {
        Random rnd = ThreadLocalRandom.current();
        for (int i = arr.length - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            
            int tmp = arr[index];
            arr[index] = arr[i];
            arr[i] = tmp;
        }
    }
    public static void main(String args[]) {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

        shuffleArray(arr);
        
        for (int i = 0; i < arr.length; i++) {
          System.out.print(arr[i] + " ");
        }
    }
}
 
 
 
 
 
/*
run:
 
2 8 9 0 5 7 6 3 1 4 
 
*/

 



answered Oct 30, 2021 by avibootz
0 votes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MyClass {
    public static void main(String args[]) {
        Integer[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

        ArrayList<Integer> al = new ArrayList<Integer>(Arrays.asList(arr));

        Collections.shuffle(al);
        
        arr = al.toArray(arr);
        
        for (int i = 0; i < arr.length; i++) {
          System.out.print(arr[i] + " ");
        }
    }
}
 
 
 
 
 
/*
run:
 
8 2 1 5 0 3 7 9 6 4 
 
*/

 



answered Oct 30, 2021 by avibootz

Related questions

2 answers 143 views
143 views asked Nov 8, 2023 by avibootz
1 answer 163 views
2 answers 108 views
108 views asked Mar 25, 2023 by avibootz
1 answer 145 views
145 views asked Mar 29, 2021 by avibootz
1 answer 164 views
164 views asked Mar 28, 2021 by avibootz
1 answer 254 views
254 views asked Mar 15, 2021 by avibootz
1 answer 102 views
102 views asked Jan 4, 2023 by avibootz
...