combinations

Back to: **Arbitrary-Precision Math**

**The function defined here computes the total possible number of combinations there are within a population of N unique items selected in groups of R at a time. We often see this operation written something like**

**A combination of things means a mixture of things, no matter what their internal order. The only thing that is important is what items are in a group. The same items in any arrangement always equate to the same identical combination. **

/* ======================================================================== This function returns an arbitrary precision count of all total possible combinations or mixtures of (N) items taken (R) at a time. Like a hand dealt in a poker game, the sequential order in which the cards are received is NOT important, but only which cards are held in the hand, regardless of their arrangement or order. ERRORS: FALSE is returned on error, if either argument is non-numeric or out of valid range. ======================================================================== */ function bcComb_N_R ($N, $R) { // Error if either argument is non-numeric. if (!is_numeric($N) or !is_numeric($R)) {return FALSE;} // Truncate argument(s) to integer value(s) without rounding. $N = bcadd($N, 0); $R = bcadd($R, 0); // Error if either argument is out of valid range. if ($N < 0 or $R < 0 or $R > $N) {return FALSE;} // Execute loop to compute C(N, r). $C=1; for ($i=0; $i < $N-$R; $i++) {$C = bcdiv(bcmul($C, $N-$i), $i+1);} // Done. return $C; }

**Below is a random example of the function usage. Each refresh of the page will generate a new C(N, R) example.**

Total possible combinations of 27 distinct items if taken in groups of 8 at a time: The exact value of C(27, 8) = 2220075 Digits count = 7

**The following is the complete listing of the example program above.**

<?php // Combinations: C = C(N, R) // Generate random values for example. $N = mt_rand(10, 1000); $R = mt_rand(1, floor($N/2)); // Cannot exceed N value above. $C_NR = bcComb_N_R($N, $R); $DigitsCount = strlen($C_NR); print "<pre> Total possible combinations of $N distinct items if taken in groups of $R at a time: The exact value of C($N, $R) = $C_NR Digits count = $DigitsCount </pre>"; // =========================== function bcComb_N_R ($N, $R) { if (!is_numeric($N) or !is_numeric($R)) {return FALSE;} $N = bcadd($N, 0); $R = bcadd($R, 0); if ($N < 0 or $R < 0 or $R > $N) {return FALSE;} $C=1; for ($i=0; $i < $N-$R; $i++) {$C = bcdiv(bcmul($C, $N-$i), $i+1);} return $C; } ?>

combinations.txt · Last modified: 2014/04/08 01:56 (external edit)