I am trying to run something of the form

p = Permutations[Range[1,16]];
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]];

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

  • 3
    $\begingroup$ I believe this question is a duplicate of: (1283). See also: (21584) $\endgroup$ – Mr.Wizard Aug 21 '14 at 9:06
  • $\begingroup$ very strange: Length[[p]] $\endgroup$ – hieron Aug 21 '14 at 10:25
  • $\begingroup$ p becomes too big (first line) $\endgroup$ – hieron Aug 21 '14 at 10:34
  • $\begingroup$ Could you give us the explicit conditions? $\endgroup$ – 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.

| improve this answer | |

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



Bytes needed to store a single permutation

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


15! *416 /2^30 //N

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

| improve this answer | |
  • 1
    $\begingroup$ That is why the OP is asking for a way to go through the permutations without loading all permutations into the memory.... $\endgroup$ – C. E. Aug 21 '14 at 11:14
  • $\begingroup$ Bringing 15 Integers in a different order shouldn't be a problem $\endgroup$ – hieron Aug 21 '14 at 11:20
  • $\begingroup$ 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. $\endgroup$ – C. E. Aug 21 '14 at 16:07
  • $\begingroup$ I really have to get MMA10 now, thx $\endgroup$ – hieron Aug 21 '14 at 16:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.