-1

I am in need of an algorithm (preferably Java) that can find the combination of a sequence of numbers. Here is an example that I would like to achieve.

Suppose the given sequence of number is: 1 2 3

I am expecting the output to be:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1 2
1 3
2 1
2 3
3 1
3 2
1
2
3

I remember I've searched this before here in stackover flow and I found the answer but that was like 2 years ago. Now I'm doing a project and I needed that algorithm again.

Abhijit
  • 62,056
  • 18
  • 131
  • 204
it2051229
  • 339
  • 3
  • 13
  • 1
    The word you are looking for is called `Permutations`. Its heaps easy to do with a recursive function. – Jeremy Thompson Jan 10 '13 at 05:42
  • I know, I did a lot of search but most code examples are not the same as the ones that I expected, most examples are fixed size. – it2051229 Jan 10 '13 at 05:43
  • 2
    powerset...................... – Ankush Jan 10 '13 at 05:43
  • 1
    Thanks Ankush, "powerset" is the right keyword :). I'm glad I found it again. – it2051229 Jan 10 '13 at 05:47
  • @Abu agreed it is educational but some of this stuff is [phD Math](http://en.wikipedia.org/wiki/Factoradic) perhaps a small trip over to http://www.codeproject.com/Articles/37215/Permutations-in-C-Using-Recursion will do the trick. – Jeremy Thompson Jan 10 '13 at 05:48
  • Some programmers call this Algo a For loop. – Frank Jan 10 '13 at 05:49
  • possible duplicate of [Obtaining powerset of a set in java](http://stackoverflow.com/questions/1670862/obtaining-powerset-of-a-set-in-java) – tom10 Jan 10 '13 at 05:51

2 Answers2

2

Unless you want to reinvent the wheel, the itertools.permutation would do what you are looking for

num = [1, 2, 3]
from itertools import permutations, chain
perm = chain(*(permutations(num, n) for n in range(len(num),0,-1)))
print '\n'.join(' '.join(map(str,e)) for e in perm)

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1 2
1 3
2 1
2 3
3 1
3 2
1
2
3
Abhijit
  • 62,056
  • 18
  • 131
  • 204
2

Python is often referred to as "batteries included", and this is for a good reason.

permutations is available in the itertools module.

>>> from itertools import permutations
>>>
>>> l = [1,2,3]
>>> all_permutations = []
>>> for i in range(2, len(l) + 1):
...     all_permutations.extend(list(permutations(l, i)))
...
>>> all_permutations.extend(l)
>>> all_permutations
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1), 1, 2, 3]
monkut
  • 42,176
  • 24
  • 124
  • 155