Distributing all balls without repetition in C++ Program


In this tutorial, we are going to learn how to distribute n balls for k students without hurting anyone.

The idea is simple, we have n balls in different colors that need to be distributed to the students. We don't have to give more than one ball of the same color to any student. If it is possible for a student to get more than one ball of the same color, then distribution should not happen.

Let's see an example.

Input

n = 10
k = 5
ballsColors = "rrrgbrbgbr"

Output

Yes

No color is more than the number of students (k). So, no student will get more than one ball of the same color.

Let's see the steps to solve the problem.

  • Initialize the n, k, and balls colors.

  • Initialize a map to store the balls color count.

  • Iterate over the colors of the balls and find the count of each ball color.

  • Now, iterate through the count of each ball.

    • If the color of any ball is greater than the number of students, then it's not possible to distribute.

    • Else we can distribute the balls.

  • Print the result.

Example

Let's see the code.

#include <bits/stdc++.h>
using namespace std;
bool canDistributeBalls(string ballsColors, int n, int k) {
   map<char, int> charCount;
   for (int i = 0; i < n; i++) {
      charCount[ballsColors[i]]++;
   }
   map<char , int >::iterator itr;
   for(itr = charCount.begin(); itr != charCount.end(); itr++) {
      if (itr->second > k) {
         return false;
      }
   }
   return true;
}
int main() {
   int n = 10, k = 5;
   string ballsColors = "rrrgbrbgbr";
   if (canDistributeBalls(ballsColors, n, k)) {
      cout << "Yes" << endl;
   }
   else {
      cout << "No" << endl;
   }
   return 0;
}

Output

If you run to execute the above program, then you will get the following result.

Yes

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 27-Jan-2021

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements