Combinations with repetitions
This example demonstrates generating combinations with repetitions from a list of items using the library Combinatorics in Julia.
Introduction
The "combination with repetitions" algorithm allows you to obtain all possible subsets of a given size, where elements can be repeated. This is useful, for example, when calculating the number of ways to select items, if you can select the same item several times (for example, choose 2 pies from several types of pies).
This approach is used in combinatorics and probability theory problems.
# If the Combinatorics package is not installed yet, run the line:
import Pkg; Pkg.add("Combinatorics")
# Importing the Combinatorics library for working with combinatorial functions
using Combinatorics
An example of using it with an array of strings
Creating a list of lines and displaying its contents. Next, we generate all possible combinations with repetitions of length 2. Such combinations are also called "multicombinations"
# We define an array of strings — these will be our source elements.
l = ["cabbage", "potato", "The jam"] # Types of pies
# Printing headlines
println("List: ", l)
println("Combinations:")
# We go through all combinations with repetitions of length 2
for c in with_replacement_combinations(l, 2)
println(c) # We output each combination
end
Counting the number of combinations
Function with_replacement_combinations() It can also work with ranges (ranges). We count the number of three-element combinations with repetitions of numbers from 1 to 10. This corresponds to the formula of combinations with repetitions:
where – the number of different elements,
– the size of the combination.
For and will be .
# We calculate the total number of three-element combinations with repetitions from the range 1..10
length_combs = length(with_replacement_combinations(1:10, 3))
Conclusion
We have reviewed the use of the library Combinatorics in the Julia programming language for generating combinations with repetitions. We created an example with a list of pie names, displayed all possible pairs with repetitions, and calculated the total number of such triples among the integers from 1 to 10.
This allows you to efficiently perform combinatorial calculations without having to implement algorithms yourself.
The example was developed using materials from Rosetta Code