在 Julia 中生成用 2 个值填充固定向量的所有可能组合

问题描述 投票:0回答:1

我想生成一个可迭代对象,它可以计算用二进制值填充向量的所有可能方法。最好是可迭代的,因为我需要在将向量存储在矩阵内之前应用选择标准。

例如,如果向量的大小为 4,则有 16 种可能性 [1,1,1,1],[1,1,1,0],[1,1,0,1],[1,0,1,1],[0,1,1,1]等.

我尝试使用 Combinatorics.jl 作为可迭代的输出似乎很理想,但它似乎总是删除退化的安排,这不是我想要的。

vector statistics julia combinations
1个回答
0
投票

您可以使用

Iterators.product
来实现此目的,它返回其参数的笛卡尔积。它返回一个迭代器,您可以在实现它之前应用
Iterators.filter
或其他任何东西。

julia> Iterators.product(fill([0, 1], 4)...) |> collect
2×2×2×2 Array{NTuple{4, Int64}, 4}:
[:, :, 1, 1] =
 (0, 0, 0, 0)  (0, 1, 0, 0)
 (1, 0, 0, 0)  (1, 1, 0, 0)

[:, :, 2, 1] =
 (0, 0, 1, 0)  (0, 1, 1, 0)
 (1, 0, 1, 0)  (1, 1, 1, 0)

[:, :, 1, 2] =
 (0, 0, 0, 1)  (0, 1, 0, 1)
 (1, 0, 0, 1)  (1, 1, 0, 1)

[:, :, 2, 2] =
 (0, 0, 1, 1)  (0, 1, 1, 1)
 (1, 0, 1, 1)  (1, 1, 1, 1)

您可以使用

vec
函数将其作为线性向量获取,并且可以将内部元组转换为向量(如果需要),并在其上广播
collect
。所以:

julia> function twoones(n)
         p = Iterators.product(([0, 1] for _ in 1:n)...)
         # just an example selection criteria: combinations with exactly two 1's in them
         q = Iterators.filter(v -> count(!iszero, v) == 2, p)
         return collect.(vec(collect(q)))
       end
twoones (generic function with 1 method)

julia> twoones(4)
6-element Vector{Vector{Int64}}:
 [1, 1, 0, 0]
 [1, 0, 1, 0]
 [0, 1, 1, 0]
 [1, 0, 0, 1]
 [0, 1, 0, 1]
 [0, 0, 1, 1]
© www.soinside.com 2019 - 2024. All rights reserved.