How do I shuffle two arrays in same order in java

前端 未结 6 757
温柔的废话
温柔的废话 2021-01-12 01:40

I\'ve got two arrays of question and answers

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

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


        
6条回答
  •  天涯浪人
    2021-01-12 02:08

    Java Collections has a (surprisingly) simple solution to this problem: Collections.shuffle(Collection, Random) with a Random seeded with same seed.

        List quests = Arrays.asList(1, 2, 3, 4, 5);
        List 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);
    

    Note:

    Extra optimization is dangerous. This DOE NOT WORK:

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

    Originally posted at: https://stackoverflow.com/a/44863528/1506477

提交回复
热议问题