从列表中提取的所有元组的功能形式

时间:2015-02-03 13:31:56

标签: list wolfram-mathematica tuples combinations combinatorics

我有六个要素的清单

{1,2,3,4,5,6}

我想以函数形式描述所有3元组(带重复)的列表,以便

f[1]=<1,1,1>
f[2]=<1,1,2>
...
f[720]=<6,6,6>

我对Mathematica中的方法很感兴趣。

提前谢谢。

3 个答案:

答案 0 :(得分:0)

尝试http://rosettacode.org/wiki/Combinations_with_repetitions以获取多种语言的示例。

以下是他们的Mathematica示例:

DeleteDuplicates[Tuples[{"iced", "jam", "plain"}, 2],Sort[#1] == Sort[#2] &]
->{{"iced", "iced"}, {"iced", "jam"}, {"iced", "plain"}, {"jam", "jam"}, {"jam", "plain"}, {"plain", "plain"}}

Combi[x_, y_] := Binomial[(x + y) - 1, y]
Combi[3, 2]
-> 6
Combi[10, 3]
->220

还有第二个例子可以处理更大的输入尺寸,这可能更符合您的要求:

CombinWithRep[S_List, k_] := Module[{occupation, assignment},
  occupation = 
   Flatten[Permutations /@ 
     IntegerPartitions[k, {Length[S]}, Range[0, k]], 1];
  assignment = 
   Flatten[Table[ConstantArray[z, {#[[z]]}], {z, Length[#]}]] & /@ 
    occupation;
  Thread[S[[#]]] & /@ assignment
  ]

In[2]:= CombinWithRep[{"iced", "jam", "plain"}, 2]

Out[2]= {{"iced", "iced"}, {"jam", "jam"}, {"plain", 
  "plain"}, {"iced", "jam"}, {"iced", "plain"}, {"jam", "plain"}}

答案 1 :(得分:0)

除非有人友好并且给我买了mathematica的许可证,否则我无法提供mathematica解决方案。但我在F#中提供的解决方案应该很容易移植。

首先,如果你有6个中有3个重复,那么组合的数量是6 * 6 * 6 = 216.问题不是720。

let func x i =
    let lookup = 
        [|
            let ax = Array.ofList x
            for first in 0..(ax.Length - 1) do
                for second in 0..(ax.Length - 1) do
                    for third in 0..(ax.Length - 1) do
                        yield [ax.[first]; ax.[second]; ax.[third]]
        |]
    match i >= 0 && i < lookup.Length with
    | true -> lookup.[i]
    | false -> failwith "You are cheating!"

let x = [1;2;3;4;5;6]

let f = func x

printfn "%A" (f 0)
printfn "%A" (f 1)
printfn "%A" (f 2)

答案 2 :(得分:0)

set = {"e1", "e2", "e3", "e4", "e5", "e6"}
tab = Table[{i,j,k}, {i,1,6},{j,1,6}, {k,1,6}];
{set[[#[[1]]]],set[[#[[2]]]],set[[#[[3]]]]}&/@(Nest[ArrayFlatten[#,1]&,tab,2])

输出

{{"e1","e1","e1"},{"e1","e1","e2"},{"e1","e1","e3"},{"e1","e1","e4"}, {"e1", "e1","e5"}, {"e1","e1","e6"}, {"e1","e2","e1"}, {"e1","e2","e2"}....