10

Possible Duplicate:
Generating all permutations of a given string

I have an array of arbitrary length in Java, and I would like to generate all possible permutations of them. The easy way to do this for a fixed length would be a series of nested for loops, but because the array is of unknown length, that is not an option here. Is there a straightforward way to accomplish this in Java?

Community
  • 1
  • 1
chimeracoder
  • 20,648
  • 21
  • 60
  • 60
  • 2
    just type `[java] permutation` in the search box... – MByD May 03 '11 at 23:05
  • 4
    If it's an array, you can use array.length; if it's a List, you can use list.size(). I don't understand "not an option". – duffymo May 03 '11 at 23:05
  • 2
    @duffymo: So I would like to see you generating the nested for loops on the fly once you get the array length in the code ... – Jan Zyka May 03 '11 at 23:08
  • checkout guava's Collections2.permutation: https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/Collections2.java?r=HEAD#537 – Janus Troelsen Jan 19 '14 at 14:18
  • @JanZyka - It's nothing to do with nested loops, you just need a stack data structure. At the end of the day all flow control is just ifs and gotos. – CurtainDog May 15 '14 at 01:46
  • Irony man :) I just said that even though you know array.length you can't really generate array.length nested loops on the fly in your code. – Jan Zyka May 15 '14 at 05:59

2 Answers2

3

Use a recursive function, instead of loops. Each time you call the method should be on a smaller portion of the array and stop when length = 0. This link should help you design your function.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
0

It may or may not be optimal as far as performance goes, but if you're looking for a way to do it with writing relatively little code and having it be clear and maintainable, you want a recursive method rather than nested loops.

Trott
  • 66,479
  • 23
  • 173
  • 212