Combinations, Permutations and Factorials in C#
Factorials are defined as a number that is multiplied by every positive number below it, and is denoted by an exclamation mark, ie n! = n * (n – 1) * (n – 2) … 2 * 1.
This is a very easy function to write.
Combinations in Combinatorics (a branch of mathematics covering combinations and permutations) gives you the number of combinations that exist for a given sample. With combinations, items selected cannot be repeated, much like selecting names out of a hat, and then after taking one out, you do not put it back in again, and then select again until you have required amount.
So, given a set of values of size n, if you select r items from the set, the number of different combinations which you can select is given by the formula C = n! / r!(n - r)!
Here is the code to calculate this. The MathExt class is just the name of the class containing these functions, so you can replace that with wherever you have defined the factorial function.
Permutations are a little simpler than combinations. In this case, you still selecting r items out of a set of n items, however, you are able to pull out the same item more than once. Much like pulling a name out of a hat, and then putting it back in before putting another name out of the hat. C = n! / (n - r)!
The full sourcecode for the MathLib library is available at https://github.com/sjmeunier/mathlib
Originally posted on my old blog, Smoky Cogs, on 23 Oct 2009
Updated 5 Oct 2016: Updated code snippet after refactoring MathLib library