Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/src/matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -525,8 +525,8 @@ julia> pfaffians(M, 2)
6-element Vector{AbstractAlgebra.Generic.MPoly{Rational{BigInt}}}:
x1
x2
x4
x3
x4
x5
x6

Expand Down
24 changes: 16 additions & 8 deletions src/Matrix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2532,27 +2532,35 @@ end
@doc raw"""
combinations(n::Int, k::Int)

Return an array consisting of k-combinations of {1,...,n} as arrays.
Return a vector consisting of `k`-combinations of ${1,...,n}$ as vectors.

The combinations are sorted in lexicographic order.
"""
combinations(n::Int, k::Int) = combinations(1:n, k)

@doc raw"""
combinations(v::AbstractVector, k::Int)

Return an array consisting of k-combinations of a given vector v as arrays.
Return a vector consisting of `k`-combinations of a given vector `v` as vectors.

The combinations are sorted in lexicographic order.
"""
function combinations(v::AbstractVector{T}, k::Int) where T
n = length(v)
ans = Vector{T}[]
k > n && return ans
_combinations_dfs!(ans, Vector{T}(undef, k), v, n, k)
_combinations_dfs!(ans, Vector{T}(undef, k), v, n, 1, 1)
return ans
end
function _combinations_dfs!(ans::Vector{Vector{T}}, comb::Vector{T}, v::AbstractVector{T}, n::Int, k::Int) where T
k < 1 && (pushfirst!(ans, comb[:]); return)
for m in n:-1:k
comb[k] = v[m]
_combinations_dfs!(ans, comb, v, m - 1, k - 1)

function _combinations_dfs!(ans::Vector{Vector{T}}, comb::Vector{T}, v::AbstractVector{T}, n::Int, i::Int, j::Int) where T
if i > length(comb)
push!(ans, copy(comb))
return
end
for m in j:n-(length(comb)-i)
comb[i] = v[m]
_combinations_dfs!(ans, comb, v, n, i+1, m+1)
end
end

Expand Down
25 changes: 25 additions & 0 deletions test/Matrix-test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,28 @@ end
@test M * QQ(1) == QQ(1) * M == QQ.(M)
@test N * ZZ(1) == ZZ(1) * N == QQ.(N)
end

@testset "combinations" begin
combinations = AbstractAlgebra.combinations
@test combinations(0, 0) == [[]]
for n in 1:5
@test combinations(n, 0) == [[]]
@test combinations(n, 1) == [[i] for i in 1:n]
@test combinations(n, 2) == [[i, j] for i in 1:n for j in i+1:n]
@test combinations(n, 3) == [[i, j, k] for i in 1:n for j in i+1:n for k in j+1:n]
end
@test combinations(5, 3) == [
[1, 2, 3],[1, 2, 4],[1, 2, 5],[1, 3, 4],[1, 3, 5],[1, 4, 5],[2, 3, 4],[2, 3, 5],[2, 4, 5],[3, 4, 5],
]
for n in 0:10, k in 0:10
comb = combinations(n, k)
if k > n
@test isempty(comb)
elseif k == n
@test comb == [collect(1:n)]
end
@test length(comb) == binomial(n, k)
@test issorted(comb)
@test allunique(comb)
end
end
Loading