how to print an array in random order in java?
example:
int[] myArray = {5,4,3,2,1};
when printed, result should possibly be:
3 2 1 4 5
or
4 3 2 5 1
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You should look at writing a Fisher-Yates shuffle. It’s pretty easy to do, and efficient. Effectively you logically partition the array into a “shuffled” part and an “unshuffled part” – then repeatedly pick a random element from the unshuffled part and swap it with the first element from the unshuffled part, to make that part of the shuffled part.
Alternatively, create a
List<Integer>instead and then useCollections.shuffle. It’s unfortunate that there isn’t an equivalent for arrays, but Java’s type system doesn’t do terribly well in terms of making either arrays or primitives generic 🙁(I’m assuming you know how to do the printing side, and that it’s the shuffling side which is the tricky bit for you.)