How to generate a random permutation in Java?

java.util.Collections.shuffle(List); javadoc link for Collections.shuffle List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); java.util.Collections.shuffle(list); It’s worth noting that there are lots of algorithms you can use. Here is how it is implemented in the Sun JDK: public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof … Read more

How to generate all permutations of an array in sorted order?

In C++ you can use std::next_permutation to go through permutations one by one. You need to sort the characters alphabetically before calling std::next_permutation for the first time: cin>>anagrama; int len = strlen(anagrama); sort(anagrama, anagrama+len); do { cout << anagrama << endl; } while (next_permutation(anagrama, anagrama+len)); Here is a demo on ideone. If you must implement … Read more

Python recursion permutations

You want to do recursion, so you first have to find out how the recursion would work. In this case it is the following: permutation [a,b,c,…] = [a + permutation[b,c,…], b + permutation[a,c,..], …] And as a final condition: permutation [a] = [a] So the recursion splits up the list in sublists with one element … Read more