Combinatorics

This module implements the combinations and permutations of an indexable object, with duplicate elements allowed or not. Compared to another Julia package Combinatorics, the iterators return tuples instead of vectors, which greatly decreases the memory allocation times and improves the code efficiency.

AbstractCombinatorics

AbstractCombinatorics{M, C} is the abstract type of all combinatoric algorithms. It has two type parameters:

  • M: the number of elements to be taken
  • C: the type of the collection of candidate elements

To avoid memory allocation, the iteration of a concrete combinatoric algorithm returns a tuple, whose length is M and eltype is eltype(C).

Combinations and DulCombinations

Combinations{M, C} and DulCombinations generate all the combinations of M elements from an indexable collection whose type is C, with the differences being that the former forbids duplicate elements in the combinations while the latter allows.

All combinations of 2 integers taken from 1 to 3 without duplicate:

Combinations{2}(1:3) |> collect
3-element Vector{Tuple{Int64, Int64}}:
 (1, 2)
 (1, 3)
 (2, 3)

All combinations of 2 integers taken from 1 to 3 with duplicate allowed:

DulCombinations{2}(1:3) |> collect
6-element Vector{Tuple{Int64, Int64}}:
 (1, 1)
 (1, 2)
 (1, 3)
 (2, 2)
 (2, 3)
 (3, 3)

Permutations and DulPermutations

Permutations{M, C} and DulPermutations generate all the permutations of M elements from an indexable collection whose type is C, with the differences being that the former forbids duplicate elements in the permutations while the latter allows.

All permutations of 2 integers taken from 1 to 3 without duplicate:

Permutations{2}(1:3) |> collect
6-element Vector{Tuple{Int64, Int64}}:
 (1, 2)
 (1, 3)
 (2, 1)
 (2, 3)
 (3, 1)
 (3, 2)

All permutations of 2 integers taken from 1 to 3 with duplicate allowed:

DulPermutations{2}(1:3) |> collect
9-element Vector{Tuple{Int64, Int64}}:
 (1, 1)
 (1, 2)
 (1, 3)
 (2, 1)
 (2, 2)
 (2, 3)
 (3, 1)
 (3, 2)
 (3, 3)

Manual