Advertisement
MohammedShoaib

Probability of a Two Boxes Having The Same Number of Distinc

Jun 2nd, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. /*
  2. Problem Statement: https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/
  3. */
  4.  
  5. class Solution {
  6. public:
  7.     double getProbability(vector<int>& balls) {
  8.         int k, n;
  9.         double valid, total;
  10.         k = balls.size();
  11.         n = accumulate(balls.begin(), balls.end(), 0) / 2;
  12.         valid = total = 0;
  13.         vector<int> b(k);
  14.  
  15.         // helper functions
  16.         auto fact = [&](int n) {
  17.             double f = 1;
  18.             while (n)
  19.                 f *= n--;
  20.             return f;
  21.         };
  22.         auto state = [&]() {
  23.             int box_1, box_2;
  24.             double f1, f2;
  25.             if (accumulate(b.begin(), b.end(), 0) != n)
  26.                 return;
  27.             box_1 = box_2 = 0;
  28.             f1 = f2 = fact(n);
  29.             for (int i = 0; i < k; i++) {
  30.                 box_1 += b[i] > 0;
  31.                 box_2 += balls[i] - b[i] > 0;
  32.                 if (b[i]) {
  33.                     box_1++;
  34.                     f1 /= fact(b[i]);
  35.                 }
  36.                 if (balls[i] - b[i]) {
  37.                     box_2++;
  38.                     f2 /= fact(balls[i] - b[i]);
  39.                 }
  40.             }
  41.             valid += (box_1 == box_2) * f1 * f2;
  42.             total += f1 * f2;
  43.         };
  44.         function<void(int)> recurse = [&](int pos) {
  45.             if (pos == k) {
  46.                 state();
  47.                 return;
  48.             }
  49.             for (int i = 0; i <= balls[pos]; i++) {
  50.                 b[pos] = i;
  51.                 recurse(pos + 1);
  52.             }
  53.         };
  54.         recurse(0);
  55.  
  56.         return valid / total;
  57.     }
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement