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