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 172 views
172 views asked Nov 8, 2023 by avibootz
1 answer 182 views
2 answers 138 views
138 views asked Mar 25, 2023 by avibootz
1 answer 164 views
164 views asked Mar 29, 2021 by avibootz
1 answer 202 views
202 views asked Mar 28, 2021 by avibootz
1 answer 277 views
277 views asked Mar 15, 2021 by avibootz
1 answer 122 views
122 views asked Jan 4, 2023 by avibootz
...