Friends Pairing Problem In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Friends Pairing Problem In C++

Friends Pairing Problem In C++

BLUF: Mastering Friends Pairing Problem In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Friends Pairing Problem In C++

C++ is renowned for its efficiency. Learn how Friends Pairing Problem In C++ enables low-level control and high-performance computing in the tutorial below.

Introduction

The "Friends Pairing Problem in C++" is a well-known computational challenge involving the calculation of possible pairings among friends for various activities within defined constraints. This scenario presents a scenario where a group of friends is provided, and the objective is to calculate the total count of potential pairings for engaging in activities, including the choice of remaining unpaired.

The issue description typically includes the subsequent guidelines:

Each person has the option to either be paired with another individual or to stay unattached.

Some individuals may have specific preferences and desire to be paired with particular individuals. The pairings must ensure the participation of everyone, with each person either being paired with a preferred partner or remaining unpaired.

The objective is to calculate the overall count of feasible pairings that satisfy these criteria.

In addressing this issue proficiently within C++, we can utilize different strategies like dynamic programming, recursive methods, backtracking, or relevant graph theory concepts. C++ provides a diverse set of functionalities and data structures for developing effective resolutions, including arrays, vectors, maps, and the standard template library (STL) algorithms.

Usually, the approach involves breaking down the problem into smaller subproblems. Memorization or dynamic programming can be employed to improve the solution by avoiding unnecessary computations.

In this scenario, we have a set of friends and need help determining the various ways they can pair up for different tasks. The rules for pairing are straightforward: each person can either team up with someone else or choose to go solo.

Solving the "Friends Pairing Problem in C++" presents an intriguing task that demands the application of algorithmic skills and expertise in C++ programming to craft effective and elegant solutions. This problem serves as an excellent opportunity to enhance problem-solving abilities and grasp computational concepts.

Example:

Let's consider an example to demonstrate the Friends Pairing Problem in C++.

Example

#include <iostream>
#include <vector>

using namespace std;

// Function to calculate the total number of ways friends can be paired up
int countWays(int n, vector<bool>& paired, vector<vector<int>>& preferences) {
    // Find the first friend who is not paired yet
    int firstFree = -1;
    for (int i = 0; i < n; ++i) {
        if (!paired[i]) {
            firstFree = i;
            break;
        }
    }
    // If no friend is left unpaired, return 1 (base case)
    if (firstFree == -1) {
        return 1;
    }
    int ways = 0;
    // Try pairing the firstFree friend with each of their preferred friends
    for (int j = 0; j < preferences[firstFree].size(); ++j) {
        int preferred = preferences[firstFree][j];
        if (!paired[preferred]) {
            // Mark both friends as paired
          paired[firstFree] = paired[preferred] = true;
            // Recursively find ways for the remaining friends
            ways += countWays(n, paired, preferences);
            // Unmark the friends for backtracking
            paired[firstFree] = paired[preferred] = false;
        }
    }
    
    // Consider the possibility of the firstFree friend staying unpaired
    paired[firstFree] = true;
    ways += countWays(n, paired, preferences);
    paired[firstFree] = false;
    
    return ways;
}
int main() {
    int n; // Number of friends
    cout << "Enter the number of friends: ";
    cin >> n;
    // Vector to store preferences of each friend
    vector<vector<int>> preferences(n);
    // Input the preferences for each friend
    for (int i = 0; i < n; ++i) {
        cout << "Enter the number of preferences for friend " << i+1 << ": ";
       int m;
        cin >> m;
        cout << "Enter the preferences for friend " << i+1 << ": ";
        for (int j = 0; j < m; ++j) {
            int pref;
            cin >> pref;
            preferences[i].push_back(pref - 1); // Adjusting index to 0-based
        }
    }
    // Vector to keep track of whether each friend is paired or not
    vector<bool> paired(n, false);
    // Calculate and output the total number of ways friends can be paired up
    int totalWays = countWays(n, paired, preferences);
    cout << "Total number of ways friends can be paired up: " << totalWays << endl;

    return 0;
}

Output:

Output

Enter the number of friends: 3
Enter the number of preferences for friend 1: 2
Enter the preferences for friend 1: 2 3
Enter the number of preferences for friend 2: 2
Enter the preferences for friend 2: 1 3
Enter the number of preferences for friend 3: 2
Enter the preferences for friend 3: 1 2
Total number of ways friends can be paired up: 4

Explanation:

  • The program begins by incorporating the fundamental header files, iostream for input/output operations, and vector for efficient data storage. It immediately announces that it will utilize the std namespace for convenience.
  • The primary function begins by questioning the user for the number of friends (n). It subsequently creates a vector called preferences, which contains the preferences of each buddy. The user enters the number of preferences for each buddy, and the application stores those choices in the preferences vector.
  • After initializing the vector paired to keep track of the degree to which each buddy is paired together, the main function invokes the countWays function to determine the aggregate amount of ways friends could have been paired. The result is subsequently presented to the user.
  • For each unpaired buddy, the function cycles through one of their favorite friends and attempts to pair them up. If a favorite buddy is also unpaired, both friends are marked as paired, and this procedure is repeated recursively to search for other pairings.
  • Furthermore, the program takes into account the potential that the first unpaired friend will stay unpaired and search for pairings without them recursively. This stage makes certain that all conceivable outcomes are considered.
  • Conclusion:

In summary, the C++ version of the "Friends Pairing Problem" demonstrates the efficient resolution of a combinatorial challenge through the application of recursive backtracking. The program determines the overall count of possible friend pairings by considering each friend's preferences and systematically exploring all feasible combinations.

The framework of the code enables users to input the number of friends and their preferences, offering adaptability across different scenarios. The software effectively manages the pairing process by utilizing vectors to store data and boolean flags to keep track of matched companions.

The execution prioritizes fundamental programming concepts such as recursion, backtracking, and data structures, establishing it as a valuable tool for mastering algorithmic approaches to problem-solving.

Moreover, the code's readability and lucidity make it accessible to developers at any skill level.

The "Friends Pairing Problem in C++" showcases how algorithmic challenges can be effectively addressed using structured methods, demonstrating problem-solving strategies and programming approaches.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience