如果我有
a=[1,3,5,7,9]
b=[2,4,6,8,10]
我希望通过排序创建两个列表中长度为5的每个组合。
到目前为止,我可以通过以下方式获得所有可能的组合:
ab=hcat(a,b)
collect(combinations(ab,5))
但我想只收到32个(在这种情况下)有序组合。
类似于我正在寻找的函数将是Mathematica中的元组[Transpose @ {a,b}]函数。
编辑: Mathematica输出如下
a = {1, 3, 5, 7, 9};
b = {2, 4, 6, 8, 10};
combin = Tuples[Transpose@{a, b}]
Length[combin]
Out[1]:= {{1, 3, 5, 7, 9}, {1, 3, 5, 7, 10}, {1, 3, 5, 8, 9}, {1, 3, 5, 8,
10}, {1, 3, 6, 7, 9}, {1, 3, 6, 7, 10}, {1, 3, 6, 8, 9}, {1, 3, 6,
8, 10}, {1, 4, 5, 7, 9}, {1, 4, 5, 7, 10}, {1, 4, 5, 8, 9}, {1, 4,
5, 8, 10}, {1, 4, 6, 7, 9}, {1, 4, 6, 7, 10}, {1, 4, 6, 8, 9}, {1,
4, 6, 8, 10}, {2, 3, 5, 7, 9}, {2, 3, 5, 7, 10}, {2, 3, 5, 8,
9}, {2, 3, 5, 8, 10}, {2, 3, 6, 7, 9}, {2, 3, 6, 7, 10}, {2, 3, 6,
8, 9}, {2, 3, 6, 8, 10}, {2, 4, 5, 7, 9}, {2, 4, 5, 7, 10}, {2, 4,
5, 8, 9}, {2, 4, 5, 8, 10}, {2, 4, 6, 7, 9}, {2, 4, 6, 7, 10}, {2,
4, 6, 8, 9}, {2, 4, 6, 8, 10}}
Out[2]:= 32
答案 0 :(得分:5)
这是使用Base.product
的v0.5解决方案。
使用
a = [1,3,5,7,9]
b = [2,4,6,8,10]
创建元组数组
julia> vec(collect(Base.product(zip(a, b)...)))
32-element Array{Tuple{Int64,Int64,Int64,Int64,Int64},1}:
(1,3,5,7,9)
(2,3,5,7,9)
(1,4,5,7,9)
(2,4,5,7,9)
(1,3,6,7,9)
(2,3,6,7,9)
(1,4,6,7,9)
(2,4,6,7,9)
(1,3,5,8,9)
(2,3,5,8,9)
⋮
(2,4,6,7,10)
(1,3,5,8,10)
(2,3,5,8,10)
(1,4,5,8,10)
(2,4,5,8,10)
(1,3,6,8,10)
(2,3,6,8,10)
(1,4,6,8,10)
(2,4,6,8,10)
并将该结果收集到矩阵中
julia> hcat((collect(row) for row in ans)...)
5×32 Array{Int64,2}:
1 2 1 2 1 2 1 2 1 2 1 2 1 … 2 1 2 1 2 1 2 1 2
3 3 4 4 3 3 4 4 3 3 4 4 3 4 3 3 4 4 3 3 4 4
5 5 5 5 6 6 6 6 5 5 5 5 6 6 5 5 5 5 6 6 6 6
7 7 7 7 7 7 7 7 8 8 8 8 8 7 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10
答案 1 :(得分:2)
有一个包Iterators.jl。通过使用它(首先,您应该按Pkg.add("Iterators")
安装),您可以执行以下操作:
using Iterators
for p in product([1,2],[3,4],[5,6],[7,8],[9,10])
@show p
end
输出:
p = (1,3,5,7,9)
p = (2,3,5,7,9)
p = (1,4,5,7,9)
p = (2,4,5,7,9)
p = (1,3,6,7,9)
p = (2,3,6,7,9)
p = (1,4,6,7,9)
p = (2,4,6,7,9)
p = (1,3,5,8,9)
p = (2,3,5,8,9)
p = (1,4,5,8,9)
p = (2,4,5,8,9)
p = (1,3,6,8,9)
p = (2,3,6,8,9)
p = (1,4,6,8,9)
p = (2,4,6,8,9)
p = (1,3,5,7,10)
p = (2,3,5,7,10)
p = (1,4,5,7,10)
p = (2,4,5,7,10)
p = (1,3,6,7,10)
p = (2,3,6,7,10)
p = (1,4,6,7,10)
p = (2,4,6,7,10)
p = (1,3,5,8,10)
p = (2,3,5,8,10)
p = (1,4,5,8,10)
p = (2,4,5,8,10)
p = (1,3,6,8,10)
p = (2,3,6,8,10)
p = (1,4,6,8,10)
p = (2,4,6,8,10)
修改强>
要将结果作为数组或矩阵数组得到,您可以这样做:
arr = Any[]
for p in product([1,2],[3,4],[5,6],[7,8],[9,10])
push!(arr,[y for y in p])
end
# now arr is array of arrays. If you want matrix:
hcat(arr...)
答案 2 :(得分:1)
可能最简单的解决方案是简单地过滤掉未分类的元素; filter(issorted, …)
应该做到这一点。然而,这产生了26个元素,所以也许我误解了你的意图:
julia> collect(filter(issorted, combinations(ab,5)))
26-element Array{Array{Int64,1},1}:
[1,3,5,7,9]
[1,3,5,7,8]
⋮