Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all permutations of all lengths

Tags:

permutation

How would you generate all the possible permutations of list b(1,6,8,3,9,5) including ones of different length? Example:

List a = [1,2,3]
generateperms(a)
1,2,3
3,1,2
3,2,1
1,3,2
2,1,3
2,3,1
2,3
1,2
1,3
2,1
3,2
3,1

And so forth and getting all the permutarions of each length?

EDIT: I'm just going to use this, written in python, works well enough:

import itertools  
a = ['a','b','c']  
for i in range(len(a)):  
    print list(itertools.permutations(a,i+1))  
like image 741
a sandwhich Avatar asked Nov 02 '10 04:11

a sandwhich


People also ask

How do you generate all permutations of an array?

You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element.


2 Answers

I think that would be all permutations of each subset.

The easiest way to return subsets is to consider all binary integers from 0 (the empty set) through the length of your input list (the complete set). So you count from 0 through and including 2**(length(input)) and use the results to mask off all elements to exclude from that particular subset.

From there you should be able to use any of the many examples of code out on the 'net for returning permutations.

like image 69
Jim Dennis Avatar answered Sep 18 '22 19:09

Jim Dennis


I'd suggest starting with something simpler. Suppose l is a list with n elements. First, can you write a function to generate all permutations of l which have a fixed length k? Then, can you find a way to call that function repeatedly with different k values to generate the permutations of length 0, all permutations of length 1, all permutations of length 2, and so on until you get to n?

like image 42
bcat Avatar answered Sep 18 '22 19:09

bcat