I am trying to create an algorithm where the method takes in an ArrayList and the length of the output is specified. The job of the method is to print all possible permutations of the items os the specified arraylist. For eg, if arraylist is 1,2 and length given is 3, it should give output as 112,122,121,212
- I'm voting to close this question as off-topic because StackOverflow isn't a code writing service. What is your question?Eiko– Eiko2016-06-16 10:47:44 +00:00Commented Jun 16, 2016 at 10:47
- Possible duplicate of Generating all possible permutations of a list recursivelyCarrol– Carrol2019-09-24 07:40:55 +00:00Commented Sep 24, 2019 at 7:40
Add a comment |
1 Answer
The resultant can be built by recursively adding all the possible characters to an existing result until you get to the wished length. You start with an empty result. The algorithm for this is pretty easy:
public static void main(String... arg) { int n = 2; int l = 3; List<String> a = new ArrayList<>(); for (int i = 0; i < n; i++) { a.add(Integer.toString(i+1)); } perm(a, "", l); } private static void perm(List<String> a, String result, int l) { if (result.length() == l) { System.out.println(result); return; } for (int i = 0; i < a.size(); i++) { String nr = result + a.get(i); perm(a, nr,l ); } } output:
111 112 121 122 211 212 221 222 10 Comments
S.Else
how would I be able to get the result as {1,1,1},{1,1,2}etc.
Liviu Stirb
@S.Else you mean a list of lists?
S.Else
I'd actually like to give out a list every time
Liviu Stirb
@S.Else instead of System.out.println(result); you can push the result in a list that it is a field of the class. Instead of String nr = result + a.get(i); create a new list from the previous list and add the token at the end of it.
S.Else
just for clarification, if (result.length() == l) happens more than just one time, correct???
|