Home > Backend Development > C++ > C++ takes k elements as a group and takes the arrangement of r elements from n elements.

C++ takes k elements as a group and takes the arrangement of r elements from n elements.

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-07 20:37:02
forward
1112 people have browsed it

C++ takes k elements as a group and takes the arrangement of r elements from n elements.

Given n, r, k, now we have to figure out how to select r items from n so that specific k items always appear together, eg.

Input : n = 8, r = 5, k = 2

Output : 960


Input : n = 6, r = 2, k = 2

Output : 2
Copy after login

We need some knowledge to solve this problem, because this problem requires us to find the arrangement of n and r such that k objects come together.

Solution

We need to formulate a formula for this problem, which will give us the answer.

Example

#include <bits/stdc++.h>
using namespace std;
int fact(int n){ // function to calculate factorial of a number
    if(n <= 1)
        return 1;
    return n * fact(n-1);
}
int npr(int n, int r){ // finding permutation
    int pnr = fact(n) / fact(n - r);
    return pnr;
}
int countPermutations(int n, int r, int k){ // the formula that we came up with
    return fact(k) * (r - k + 1) * npr(n - k, r - k);
}
int main(){
    int n = 8;
    int r = 5;
    int k = 2;
    cout << countPermutations(n, r, k);
    return 0;
}
Copy after login

Output

960
Copy after login

Explanation of the above code

In the above method, we try to design our formula to calculate the answer to this question , the formula we designed is (k!) * (r - k 1) * P(n-k, r-k). (P(x, y) is the number of permutations that select y from x), so we come up with the formula, and calculate the answer.

Conclusion

In this tutorial we solve the problem of finding permutations that put r things together with k things at a time. We also learned the C program for this problem and the complete method to solve it (Normal).

We can write the same program in other languages, such as C, java, python and other languages. We hope you found this tutorial helpful.

The above is the detailed content of C++ takes k elements as a group and takes the arrangement of r elements from n elements.. For more information, please follow other related articles on the PHP Chinese website!

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