Friend Pairing Problem


In a group, there is n number of friends. Each person can remain single or be paired with some other friend. Find the total number of ways, in which friends can remain single or can be paired up.

If one pair has two friends’ p and q, then (p, q) or (q, p) are same. 

For a group of n friends, let f(n) be the number of ways how they can be paired up or remain single. Then either the nth person remains single, or paired up. If the nth person is single, then we recur for (n - 1) friends. If the nth person is paired up with any of the remaining (n-1) person, then, we recur (n-1) *f(n-2).

Input and Output

Input:
The number of friends. Say 5.
Output:
The possible way to pair them. Here the answer is 26.

Algorithm

countPairs(n)

Input: Number of friends.

Output: Number of ways to pair n friends.

Begin
   define pair array of size n + 1
   pair[0] := 0, pair[1] := 1 and pair[2] := 2

   for i in range 3 to n, do
      pair[i] := pair[i-1] + (i+1)*pairs[i-2]
   done

   pair[n]
End

Example

#include <iostream>
using namespace std;

int countPairs(int n) {
   int pairs[n + 1];             //number of pairs for ith number

   //for number 0 to 2, there are 0 to 2 possible combination
   pairs[0] = 0;
   pairs[1] = 1;
   pairs[2] = 2;

   for (int i = 3; i <= n; i++)             //fill array for 3 to n numbers
      pairs[i] = pairs[i-1] + (i-1) * pairs[i-2];

   return pairs[n];
}

int main() {
   int n;
   cout << "Enter numbers: "; cin >> n;
   cout << "Number of ways to pair "<<n<<" friends: " << countPairs(n);
}

Output

Enter numbers: 5
Number of ways to pair 5 friends: 26

Updated on: 17-Jun-2020

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements