julia - 在 Julia 中排序的两个数组的组合

标签 julia combinatorics

如果我有

a=[1,3,5,7,9]
b=[2,4,6,8,10]

我想通过排序创建两个列表中长度为 5 的每个组合。

到目前为止,我可以通过以下方式获得所有可能的组合:
ab=hcat(a,b)
collect(combinations(ab,5))

但我只想收到 32 个(在这种情况下)有序组合。

一个类似于我正在寻找的函数是 Mathematica 中的 Tuples[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

最佳答案

这是使用 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

关于julia - 在 Julia 中排序的两个数组的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40227282/

相关文章:

julia - 使用 Plots.jl 显示多个图

floating-point - 在Julia Lang中将float转换为int

linq - 在 Julia 字典中查询某些值

java - 组合java的组合

math - 密码学中的困惑和排列

algorithm - 计算组合乐高积木的方法数量

julia - 从 Julia 中的矩阵中减去向量的最佳方法

multidimensional-array - 如何在 Julia 的特定轴上对高阶多维数组(或张量)进行切片?

获得达到目标概率的算法

algorithm - 互置换算法