C++ Permutations of n things Taken r at a Time with k Things Together


Given n, r, k, now we have to find how we can select r things from n so that specific k things always occur together, for example.

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

Output : 960


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

Output : 2

We need a little knowledge for this problem because this problem is asking us to find the permutation of n and r such that k things come together.

Approach to Find the Solution

We need to formulate our formula for this question, and that will give us our 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 approach, we try to devise our formula for calculating our answer as for this problem, the formula that we devised is (k!) * (r - k + 1) * P(n-k, r-k). ( P(x, y) is the number of permutations of selection y from x) hence we put up our formula, and we calculate the answer.

Conclusion

In this tutorial, we solve a problem to find Permutations of n things taken r at a time with k things together. We also learned the C++ program for this problem and the complete approach ( Normal) by which we solved this problem.

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

Updated on: 25-Nov-2021

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements