1

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

S.Else
  • 47
  • 2
  • 7
  • I'm voting to close this question as off-topic because StackOverflow isn't a code writing service. What is your question? – Eiko Jun 16 '16 at 10:47
  • Possible duplicate of [Generating all possible permutations of a list recursively](https://stackoverflow.com/questions/10305153/generating-all-possible-permutations-of-a-list-recursively) – Carrol Sep 24 '19 at 07:40

1 Answers1

2

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
Liviu Stirb
  • 5,876
  • 3
  • 35
  • 40
  • how would I be able to get the result as {1,1,1},{1,1,2}etc. – S.Else Jun 16 '16 at 11:07
  • @S.Else you mean a list of lists? – Liviu Stirb Jun 16 '16 at 11:26
  • I'd actually like to give out a list every time – S.Else Jun 16 '16 at 12:11
  • @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. – Liviu Stirb Jun 16 '16 at 12:46
  • just for clarification, if (result.length() == l) happens more than just one time, correct??? – S.Else Jun 16 '16 at 12:52
  • @S.Else yes, each one is a different "permutation". – Liviu Stirb Jun 16 '16 at 13:00
  • thanks a lot, sorry for bothering you again but do you know how i could limit the no. of different entries. For eg: input maybe 1,2,3 but i only want result as combination of 1 and 2 or 2 and 3 or 1 and 3 – S.Else Jun 16 '16 at 13:04
  • @S.Else this is a different question. if this or any answer has solved your question please consider by clicking the check-mark. for your new question; you can check when adding to the list/printing if it matches your conditions. – Liviu Stirb Jun 16 '16 at 13:28
  • Sorry, to have to unselect your answer but it causing stackoverflow error – S.Else Jun 16 '16 at 14:11
  • @S.Else If you work with large sets i'm pretty sure it does – Liviu Stirb Jun 16 '16 at 19:44