当前位置: 动力学知识库 > 问答 > 编程问答 >

java - shuffling a list multiple times

问题描述:

I have 2 lists that I shuffle at the beginning of my oncreate() and then I would like to shuffle them again at a later point when a "new game" button is pressed. The first time they are shuffled I used:

final Random rnd = new Random();

final int seed = rnd.nextInt();

rnd.setSeed(seed);

Collections.shuffle(Arrays.asList(answerChoices),rnd);

rnd.setSeed(seed);

Collections.shuffle((resources),rnd);

And everything works fine. However when I try to shuffle them again when a "new game" button is pressed i tried using the same as above and I tried changing the name of both rnd and seed and it doesnt work properly. After the second shuffle the lists do not match as they should. any suggestions as to what I should try?

网友答案:

A possible solution to your problem is to wrap the values in your two lists in a class. Then add objects of those class to one list and shuffle that, for example:

public class Test {
    public static void main(String[] args) {
        Random rnd = new Random();
        int seed = rnd.nextInt();
        rnd.setSeed(seed);
        List<Pair> pairs = new ArrayList<Pair>();

        pairs.add(new Pair(1, "else"));
        pairs.add(new Pair(2, "bar"));
        pairs.add(new Pair(3, "pair"));

        Collections.shuffle(pairs, rnd);

        for (Pair pair : pairs) {
            System.out.println(pair.drawable + " " + pair.sequence);
        }
    }

}

class Pair {
    int drawable;
    CharSequence sequence;

    Pair(int drawable, CharSequence sequence) {
        this.drawable = drawable;
        this.sequence = sequence;
    }
}

Running the code repeatedly will result in different ordered lists, but the values will still be paired.

分享给朋友:
您可能感兴趣的文章:
随机阅读: