'Get every combination (order is important) in vector with given size and elements [closed]

I want to create every possible coloring in a vector for a given size of the vector (amount of vertices) and given possible elements (possible colors)

as an example:

for a graph with 3 vertices and I want to color it with 3 colors, I want the following possible vectors, that are gonna be my possible colorings:

0 0 0

0 0 1

0 0 2

...

2 1 1

2 1 2

...

2 0 0

1 0 0

as you can see I want both combinations like "0 0 1" and "1 0 0".

is there any way to do this efficiently?



Solution 1:[1]

This is definitely possible. Refer to the below code. It also works with all the other ASCII characters. You can modify it in order to meet your demands:

#include <iostream>
#include <vector>
#include <string>

inline std::vector<std::string> GetCombinations(const char min_dig, const char max_dig, int len)
{
    std::vector<std::string> combinations;
    std::string combination(len, min_dig);

    while (true)
    {
        if (combination[len - 1] == max_dig)
        {
            combination[len - 1] = min_dig;

            int increment_index = len - 2;
            while (increment_index >= 0 && combination[increment_index] == max_dig)
            {
                combination[increment_index] = min_dig;
                increment_index--;
                if (increment_index == -1) break;
            }
            if (increment_index == -1) break;
            combination[increment_index]++;
            combinations.push_back(combination); continue;
        }
        combination[len - 1]++;
        combinations.push_back(combination);
    }

    return combinations;
}

int main()
{
    std::cout << "Enter the number of digits: "; int len; std::cin >> len;
    std::cout << std::endl;
    
    // '0' is the minimum character. '2' is the maximum character. len is the length.
    std::vector<std::string> combinations = GetCombinations('0', '2', len);

    for (auto& i : combinations)
    {
        std::cout << i << std::endl;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Solved Games