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 random (shuffle) array of integers in Java

1 Answer

0 votes
import java.util.Arrays;
import java.util.Random;

public class MyClass {
    private static void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		
		arr[i] = arr[j];
		arr[j] = tmp;
	}

	public static void shuffle(int arr[]) {
		for (int i = arr.length - 1; i >= 1; i--) {
			Random rand = new Random();
			int j = rand.nextInt(i + 1);
			swap(arr, i, j);
		}
	}
    public static void main(String args[]) {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };

		shuffle(arr);

		System.out.println(Arrays.toString(arr));
    }
}


/*
run:

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

*/

 



answered Feb 24, 2019 by avibootz

Related questions

1 answer 159 views
1 answer 143 views
2 answers 143 views
143 views asked Nov 8, 2023 by avibootz
2 answers 140 views
140 views asked Oct 30, 2021 by avibootz
1 answer 82 views
5 answers 286 views
...