Re: generating all combinations.
- To: mathgroup at smc.vnet.net
- Subject: [mg22422] Re: [mg22395] generating all combinations.
- From: "Mark Harder" <harderm at ucs.orst.edu>
- Date: Wed, 1 Mar 2000 00:40:20 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
Wen-Feng and everyone, I think what Wen-Feng is trying to do is construct the n-fold CartesianProduct of a set, which is the list of all ordered n-element lists of members of the set. The Combinatorica package contains an attempt at a CartesianProduct function, but it only works correctly when applied to a pair of sets. Reiterating this function with a prior result does *not* result in a CartesianProduct of higher power (in Mathematica 3.0.x). Load DiscreteMath`Combinatorica` and try the following to see the problem: set={1,2}; CartesianProduct[set,set] CartesianProduct[set,%] The 2-fold CP is o.k., but the 3-fold product should be a list of 8 triples, and it isn't. In order to get the correct answer, you have to Flatten & re- Partition, like Wen-Feng has done, and I couldn't figure out how to do that automatically for the general n-fold case. Somebody at Wolfram should fix this. Here is the work-around that I found. The recursive function ExponentialSet is a little long, but using it is easy: <<DiscreteMath`Combinatorica` ClearAll[ExponentialSet]; ExponentialSet[set_List,1]:= set; ExponentialSet[set_List,2]:=CartesianProduct[set,set]; ExponentialSet[set_List,n_]:= Map[Flatten,CartesianProduct[set,ExponentialSet[set,n-1] ] ]; eg. In[67]:= set2={1,2}; exponentialSet[set2,3] Out[67]= {{1,1,1},{1,1,2},{1,2,1},{1,2,2},{2,1,1},{2,1,2},{2,2,1},{2,2,2}} OK? -mark harder harderm at ucs.orst.edu -----Original Message----- From: Wen-Feng Hsiao <d8442803 at student.nsysu.edu.tw> To: mathgroup at smc.vnet.net Subject: [mg22422] [mg22395] generating all combinations. >Dear all, > >I would like to generate all the combinations n-digit lists, which can >vary between a certain range and duplications are allowed. The three >digits with range between -2 to 2 is the following: > >allcomb = > Table[{i, j, k}, {i, -2, 2}, {j, -2, 2}, {k, -2, 2}]; >fltcomb = Partition[Flatten[allcomb], 3]; > >Is there a more succinct way to do that? If I would like to expand the >code to 10 digits, the code would looks clumsy. > >Thanks for your help. > >Wen-Feng > >