Given two integers n and r, I want to generate all possible combinations with the following rules:
- There are
ndistinct numbers to choose from,1, 2, ..., n; - Each combination should have
relements; - A combination may contain more than one of an element, for instance
(1,2,2)is valid; - Order matters, i.e.
(1,2,3)and(1,3,2)are considered distinct; - However, two combinations are considered equivalent if one is a cyclic permutation of the other; for instance,
(1,2,3)and(2,3,1)are considered duplicates.
Examples:
n=3, r=2
11 distinct combinations
(1,1,1), (1,1,2), (1,1,3), (1,2,2), (1,2,3), (1,3,2), (1,3,3), (2,2,2), (2,2,3), (2,3,3) and (3,3,3)
n=2, r=4
6 distinct combinations
(1,1,1,1), (1,1,1,2), (1,1,2,2), (1,2,1,2), (1,2,2,2), (2,2,2,2)
What is the algorithm for it? And how to implement it in c++? Thank you in advance for advice.
Here is a naive solution in python:
{1, 2, ...,n}with itselfrtimes;This means we must have some way to compare combinations, and for instance, only keep the smallest combination of every equivalency class.
You mentioned that you wanted to implement the algorithm in C++. The
productfunction in the python code behaves just like a bigfor-loop that generates all the combinations in the Cartesian product. See this related question to implement Cartesian product in C++: Is it possible to execute n number of nested "loops(any)" where n is given?.