Serge's World

Blogging about software development, astronomy, genealogy and more.

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.

public static long Factorial(int num)  
{  
    long fact = 1;  
    for (int i = 2; i <= num; i++)  
    {  
        fact = fact * i;  
    }  
    return fact;  
}

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.

public static int Combination(int n, int r)
{
	int Comb = 0;
	Comb = (int)(MathExt.Factorial(n) / (MathExt.Factorial(r) * MathExt.Factorial(n - r)));
	return Comb;
}

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)!

public static int Permutation(int n, int r)
{
	int Perm = 0;
	Perm = (int)(MathExt.Factorial(n) / MathExt.Factorial(n - r));
	return Perm;
}

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

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)