10

我有两组问题和答案

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

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

我曾经Collections.shuffle(Arrays.asList(questions);对每个数组进行洗牌。我如何洗牌每个数组,以便在洗牌后它们保持相同的顺序?

4

6 回答 6

12

您可以改组一个包含索引的新数组。然后从第一个索引中获取两个数组中的元素。

List<Integer> indexArray = Arrays.asList(0, 1, 2);

Collections.shuffle(indexArray);

String question = questions[indexArray.get(0)];
String answer = answers[indexArray.get(0)];

当然,正如其他答案所暗示的那样,创建一个class包含questions并且answers将是一种更面向对象的方式。这样,与当前方法相比,您只需维护一个Listor 。array3 arrays

于 2012-11-23T16:40:54.957 回答
8

创建一个将问题和答案放在一起的类将是一个更简单且更面向对象的解决方案:

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

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

进而:

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

Collections.shuffle(Arrays.asList(questions));
于 2012-11-23T16:49:13.953 回答
6

创建一个类QuestionAndAnswer并使用该类的数组。

于 2012-11-23T16:44:59.287 回答
3

Java Collections 对这个问题有一个(令人惊讶的)简单的解决方案:Collections.shuffle(Collection<?>, Random)使用Random具有相同种子的种子。

    List<Integer> quests = Arrays.asList(1, 2, 3, 4, 5);
    List<Integer> answers = Arrays.asList(10, 20, 30, 40, 50);

    long seed = System.nanoTime();
    Collections.shuffle(quests, new Random(seed));
    Collections.shuffle(answers, new Random(seed));

    System.out.println(quests);
    System.out.println(answers);

笔记:

额外的优化是危险的。 这不起作用:

    long seed = System.nanoTime();
    Random rnd = new Random(seed);
    Collections.shuffle(quests, rnd);
    Collections.shuffle(answers, rnd);

原贴于:https ://stackoverflow.com/a/44863528/1506477

于 2017-07-01T17:15:29.947 回答
2

您可以对具有问题/答案索引的额外整数数组进行洗牌,而不是对答案和问题进行洗牌,然后使用洗牌索引从相应的数组中提取问题和答案。

于 2012-11-23T16:55:23.893 回答
0

想法来自: http ://www.vogella.com/tutorials/JavaAlgorithmsShuffle/article.html

public static void shuffle2ArraysTogther(String[] a, String[] b) {
    if(a.length == b.length) {
        int n = a.length;
        Random random = new Random();
        random.nextInt();
        for (int i = 0; i < n; i++) {
            int change = i + random.nextInt(n - i);
            swap(a, i, change);
            swap(b, i, change);
        }
    }
}

private static void swap(String[] a, int i, int change) {
    String helper = a[i];
    a[i] = a[change];
    a[change] = helper;
}

private static void swap(String[] a, int i, int change) {
    String helper = a[i];
    a[i] = a[change];
    a[change] = helper;
}
String questions[] = {
    "Q1?",
    "Q2?",
    "Q3?"
};

String answers[] = {
    "A1?",
    "A2?",
    "A3?"
};
shuffle2ArraysTogther(questions, answers);
for (String i : questions) {
    System.out.println(i);
}
for (String i : answers) {
    System.out.println(i);
}
于 2018-09-24T20:31:00.297 回答