Mathematica枚举组合

时间:2016-02-12 08:54:04

标签: wolfram-mathematica combinations

我需要枚举我拥有的3组值的组合。例如,这些组是(a,b,c,d),(e,f,g,h),(i,j,k,l)。总组合为4x4x4 = 64。 有谁有想法,我如何定义这些组合的升序编号? 我已经用这种形式写了一些东西:

Do[Do[Do[x["formula is needed here"]=s[[i,j,k]],{k,1,4}],{j,1,4}],{i,1,4}]

我找不到组合编号的公式。我读过一些关于"生成数学组合的第m个词典元素的内容"但我失去了比帮助更多。 x应该取值1,2,3,....,64。 谢谢你的建议!

2 个答案:

答案 0 :(得分:2)

if you need a "formula" for the 'nth' tuple it looks like this:

posts = [i.body for i in Email.query.all()]

True

so then if you want say the 12'th combination of your sets you could do something like this:

{ Floor[(# - 1)/16      ] + 1,
  Floor[Mod[# - 1, 16]/4] + 1 , 
  Floor[Mod[# - 1, 4]   ] + 1 } & /@ Range[64] ==
  Tuples[Range[4], 3]

{a, g, l}

note that whatever you are doing it is almost always best to use the built in object oriented functions.

({ 
     Floor[(# - 1)/16] + 1,
     Floor[Mod[# - 1, 16]/4 + 1] ,
     Mod[# - 1, 4] + 1 } &@12);
{{a, b, c, d}[[%[[1]]]], {e, f, g, h}[[%[[2]]]], {i, j, k, 
   l}[[%[[3]]]]}

{a, g, l}

Edit: for completeness a generalization of the first expression:

 Tuples[{{a, b, c, d}, {e, f, g, h}, {i, j, k, l}}][[12]]

True

答案 1 :(得分:0)

Tuples[{{a, b, c, d}, {e, f, g, h}, {i, j, k, l}}]