Home  >  Article  >  Backend Development  >  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.

WBOY
WBOYforward
2023-09-07 20:37:021036browse

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

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;
}

Output

960

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:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete