1

I have an ArrayList<Integer>. Now I need to find all possible permutations of the integers in this array and then extract each Integer from my list of permutations. (There is no repetition, each number occurs exactly once). This is what I do currently:

for (int a : myList) {
     if (a != 0 && a < 10) {
        myString = myString + Integer.toString(a);
     }
}

permutation(myString);
private ArrayList<String> my_permutations = new ArrayList<>();

So essentially I turn my ArrayList into a String and run the following functions on it :

public void permutation(String str) {
    permutation("", str);
}

private void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) {
        my_permutations.add(prefix);
    } else {
        for (int i = 0; i < n; i++) {
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
        }
    }
}

This works fine with digits 1-9, however it breaks with 10+. Is there any way I can do this in a better way? At a latter stage, I extract Integers from the Strings one by one by looping through the String and doing :

Integer.parseInt(String.valueOf(single_string.charAt(i));

So for example if my ArrayList contains 1,2,3, I obtain the String "123", and the following permutations:

"123"
"132"
"312"
"321"
"213"
"231"

After that I loop through each permutation and extract individual Integers so I would obtain 1 2 3 from the first one, 1 3 2 from the second one etc

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Alk
  • 5,215
  • 8
  • 47
  • 116
  • well I suppose it breaks because you use chars – ItamarG3 Oct 14 '16 at 16:45
  • Sounds like you need some type of generator function. – Mr. Polywhirl Oct 14 '16 at 16:48
  • I looked at this http://stackoverflow.com/questions/11343848/java-permutation-of-arraylist-elements-integer-cant-get-it-to-work-proper but I'm not sure what the two additional variables passed to his function are for – Alk Oct 14 '16 at 16:50
  • Possible duplicate of [Permutation of array](http://stackoverflow.com/questions/2920315/permutation-of-array) – prophet1906 Oct 14 '16 at 16:53
  • better way -- translate this code so it uses `List` (i.e., use `list.get(i)`, `list.subList(...)`, etc). Even better -- there are algorithms to generate permutations "in place", using `next permutation` step: http://stackoverflow.com/a/353248/162634 – Victor Sorokin Oct 14 '16 at 16:54
  • first, [StringBuilder](http://stackoverflow.com/questions/4645020/when-to-use-stringbuilder-in-java). Also please could you further define: 'Is there any way I can do this in a better way?' - a better way how? what are you trying to accomplish (removal of strings completely?)? – Nick Bell Oct 14 '16 at 17:00
  • What I want to achieve is to have a list of all possible permutations so that I can then divide them into lists of integers. A better way so that it works for all integers, not just those less than 10 – Alk Oct 14 '16 at 17:05

0 Answers0