L
L
Leevz2018-10-16 13:24:55
Mathematics
Leevz, 2018-10-16 13:24:55

How to iterate over all permutations in C++?

The real problem is more complicated, but I only need to understand the principle itself, so it is very simplified. There are three types of letters in total: A, B and C. The input of the program is three numbers - the number of letters A, the number of letters B and, respectively, C. How can you go through all the permutations (permutations from a mathematical point of view)? It doesn't matter what to do with them, output, add or find the largest, it is important that it is simply possible to get each permutation, and not any other combinations. The letters themselves must be elements of the array. For example, the input is the numbers "1 1 1", so the corresponding combinations will be: ABC, ACB, BAC, BCA, CAB, CBA. This is a simple input, but in practice there may be, for example, such a combination of numbers - "6 2 3". Not necessarily in C++, but would be nice

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Olohtonov, 2018-10-16
@Leevz

Reduce the problem to a simpler one: put all your elements in an array and generate all its permutations.
https://en.cppreference.com/w/cpp/algorithm/next_p...

#include <algorithm>
#include <string>
#include <iostream>
 
int main()
{
    std::string s = "aba";
    std::sort(s.begin(), s.end());
    do {
        std::cout << s << '\n';
    } while(std::next_permutation(s.begin(), s.end()));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question