generating a large number of permutations using mathematica 5.2
I m using Mathematica 5.2. I used th开发者_高级运维e command Tuples to generate permutations such as:
In[1]:=Tuples[{0,1},3]
Out[1]={{0,0,0},{0,0,1},{0,1,0},{0,1,1},{1,0,0},{1,0,1},{1,1,0},{1,1,1}}
But the problem is, when I want to generate all possible permutations by placing 0 and 1 in more than 20 places, Tuples command fails to give the output because of the lack of memory capacity. for example, if I want to generate large number of permutations using 0 and 1, like,
Tuples[{0,1},25]
The command "Tuples" does not give the output, it gives a message that there is no enough memory space to generate such a large number of permutations, so how can I manage this problem? Is there any other process of generating larger permutations ? Or, if I want to generate each of the permutations one by one instead of generating simultaneously in an array like the output[1], how can I do that?
Generating a list of of those permutations in a single evaluation requires more than 3 GB of memory. Here's the output produced with Mathematica 8:
In[1]:= NumberForm[ ByteCount [ Tuples[{0, 1}, 25] ], DigitBlock -> 3]
Out[1]//NumberForm= 3,355,443,368
The Mathematica 5.2 kernel is a 32-bit executable and cannot handle the required amount of memory. You can use a Do
loop instead to produce one permutation at a time:
With[{n = 4}, Do[Print[IntegerDigits[i, 2, n]], {i, 0, 2^n - 1}]]
In your particular example, Tuples
of {0,1}
, it is much more efficient to store the results as integers.
a = Tuples[{0, 1}, 20];
b = Range[0, 2^20 - 1];
ByteCount /@ {a, b}
{83886168, 4194388}
Length /@ {a, b}
{1048576, 1048576}
a[[618021]] == IntegerDigits[ b[[618021]] , 2, 20]
True
Memory usage of tuples of length 25:
Range[0, 2^25 - 1] // ByteCount
134217812
To specifically answer the question "Or, if I want to generate each of the permutations one by one instead of generating simultaneously in an array like the output[1], how can I do that?"
Mathematica 5.2 used the Combinatorica Add-on package for NextPermutation.
In[1]:= <<"DiscreteMath`Combinatorica`"
In[2]:= somepermutation={0,1,2}; NextPermutation[somepermutation]
Out[3]= {0,2,1}
In[4]:= NextPermutation[%]
Out[4]= {1,0,2}
In[5]:= NextPermutation[%]
Out[5]= {1,2,0}
etc. But NextPermutation only permutes sets correctly, not multisets. The book below explains this and there are work-arounds.
In[6]:= somepermutation={0,1,0};NextPermutation[somepermutation]
Out[7]= {0,0,1}
In[8]:= NextPermutation[%]
Out[8]= {0,1,0}
If you plan on using Combinatorica in Mathematica then having a copy of "Computational Discrete Mathematics, Combinatorics and Graph Theory with Mathematica" by Pemmaraju and Skiena next to you will be essential. Parts of that could be better written to serve as a reference but without it you will likely find it far harder to use Combinatorica
精彩评论