Reorder a List to randomize its order in Java

╄→гoц情女王★ 提交于 2021-01-29 09:09:19

问题


I have a list with N elements, I want to randomize its order.

Preferably with the least computation, and being able to use up memory (duplicating the total).

So far I've come up with:

  • create new empty list, take first element from original list, insert it in new list on random position, order of magnitude seems O(N*N) but no extra memory is used.
  • create a new ArrayList(capacity N) (so access is O(1)), create a new hashSet and insert all possible positions (N), take the first element of the original List and insert it in a random position of the new arrayList, remove this position form the hashSet because ti has been used.
  • create a new HashSet, add all elemnts to this hashSet, and iterate over the set to create a new List and hope the order in the hashSet is random.

Seems to me the least expensive is the third option, but i'm unsure of how random the result would be. Any suggestions?


回答1:


The best way to shuffle a list is using the standard library method Collections.shuffle.

List lst = getListFromSomewhere();
Collections.shuffle(lst);

If you want to do it yourself, read up on the Fisher-Yates shuffle algorithm.




回答2:


Collections.shuffle(list); what you are looking for.




回答3:


Others already mentioned about shuffle, but if you are using gwt, shuffle is not supported and you may have to code it. Here's one approach:

public static void shuffleList(final List<String> list) {

    int length = list.size();
    Random random = new Random();

    for (int i = 0; i < length; i++) {

        // Swap index
        int swap = i + random.nextInt(length - i);      

        // Store temporarily
        String temp = list.get(i);

        // Set the values
        list.set(i, list.get(swap));
        list.set(swap, temp);

    }
}

To use, just do-

shuffleList(listOfStringsToShuffle);


来源:https://stackoverflow.com/questions/19050524/reorder-a-list-to-randomize-its-order-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!