Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shuffle two arrays in same order in java

I've got two arrays of question and answers

String questions[] = {
"Q1?",
"Q2?",
"Q3?"};

String answers[] = {
    "A1?",
    "A2?",
    "A3?"};

I used Collections.shuffle(Arrays.asList(questions); to shuffle each arrays. How do I shuffle each array so that after shuffling they maintain same order?

like image 757
Sujal Avatar asked Nov 23 '12 16:11

Sujal


People also ask

How do I shuffle two Arraylists at once?

shuffle(imgList, new Random(seed)); Using two Random objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.

How do you shuffle elements in a collection?

shuffle() method of Collections class as the class name suggests is present in utility package known as java. util that shuffles the elements in the list. There are two ways with which we can use to implement in our programs that are as follows: Using the pre-defined source of randomness.

How do you shuffle items in an ArrayList?

In order to shuffle elements of ArrayList with Java Collections, we use the Collections. shuffle() method.


1 Answers

Creating a class for holding both the question and answer together would be an easier and more OO solution:

class QuestionAnswerPair {
    private final String question;
    private final String answer;

    public QuestionAnswerPair(String question, String answer) {
        this.question = question;
        this.answer = answer;
    }
}

And then:

QuestionAnswerPair[] questions = new QuestionAnswerPair[] {
    // Put questions here
};

Collections.shuffle(Arrays.asList(questions));
like image 153
Phil K Avatar answered Oct 05 '22 01:10

Phil K