The i-th element of a permutation [duplicate]

I am trying to run something of the form

p = Permutations[Range[1,16]];
result={};
Table[If["p[[i]] satisfies some conditions",result=Append[result,p[[i]]]],{i,1,Length[[p]]}];


and I get an "out of memory error" when defining p. I am trying to find a way around this, especially since I don't really need to store Permutations[Range[1,16]] at any given point. All I want is access the i-th element of it and run some tests (for all i). I understand this might take ages but I can afford to let the program run for months, whereas the memory of the computer I am using is restricted. Any ideas?

A "proper" minimal example:

p = Permutations[Range[1,16]];
result={};
Table[If[p[[i]]==Range[1,16],result=Append[result,p[[i]]]],{i,1,Length[p]}];
result


and the expected output would be {1,2,3,4,..,16}.

marked as duplicate by Simon Woods, RunnyKine, m_goldberg, Öskå, gpapAug 21 '14 at 13:54

• I believe this question is a duplicate of: (1283). See also: (21584) – Mr.Wizard Aug 21 '14 at 9:06
• very strange: Length[[p]] – hieron Aug 21 '14 at 10:25
• p becomes too big (first line) – hieron Aug 21 '14 at 10:34
• Could you give us the explicit conditions? – Apple Aug 21 '14 at 11:57

Ok, found it. You can use the Combinatorica package. Either the function NextPermutation which allows you to iterate over the permutations or the function UnrankPermutation which does exactly what is described.

You may use package Combinatorica to get a specific permutation

Length[[p]] is an error, should be Length[p]

Just for fun:

Let's calculate the memory needed to store your list in Mathematica

Calculating the number of permutations possible

15!

1307674368000


Bytes needed to store a single permutation

ByteCount[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}]

416

15! *416 /2^30 //N
506632.5302124023


So about 500 Terrabytes are needed to store your expression in Mathematica.

• That is why the OP is asking for a way to go through the permutations without loading all permutations into the memory.... – C. E. Aug 21 '14 at 11:14
• Bringing 15 Integers in a different order shouldn't be a problem – hieron Aug 21 '14 at 11:20
• Your new answer in bold at the top is not right either. At least in V10 Permute has been moved to MMA, so you don't need the Combinatorica package to use it. But that's not even the right function, which is what Heterotic posted. – C. E. Aug 21 '14 at 16:07
• I really have to get MMA10 now, thx – hieron Aug 21 '14 at 16:09