Home > Backend Development > C++ > How Can I Efficiently Generate Combinations in C ?

How Can I Efficiently Generate Combinations in C ?

DDD
Release: 2024-12-02 00:11:11
Original
530 people have browsed it

How Can I Efficiently Generate Combinations in C  ?

Generating Combinations Efficiently in C

Determining combinations in C can be a challenging task, especially if you're looking for a flexible solution that handles varying input values.

A thoughtful approach to this problem involves employing the next_permutation function from the standard C library. This function generates all permutations of a vector incrementally. Here's how you can utilize this function:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}
Copy after login

This approach effectively creates a selection array (v) with r selector values. Subsequently, it iterates through all permutations of this selection array, printing the corresponding set members for selected positions.

For instance, if you provide the input "5 2" (S = {1, 2, 3, 4, 5} and r = 2), this algorithm will output:

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Copy after login

This method provides an efficient and generalized solution for generating combinations in C .

The above is the detailed content of How Can I Efficiently Generate Combinations in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template