Latest Updates
Latest Tweets
Fork me on GitHub

Combinatorics

Code Sample

Say you have a list of numbers and would like to shuffle them so that the items are in random order. How many such orderings (permutations) are possible?

The Combinatorics class provides methods for both counting combinations and variations and to generate them randomly:

using MathNet.Numerics;

class Test
{
    static void Main(string[] args)
    {
        int[] numbers = new int[] { 1, 2, 3, 4, 5 };
        int count = numbers.Length; // = 5
        
        double numberOfPermutations = Combinatorics.Permutations(count);
        // Will be 120 since there are 120 possible orderings for 5 numbers
        
        int[] permutation = new int[count];
        Combinatorics.RandomShuffle(numbers, permutation);
        // 'permutations' now contains the same numbers as 'numbers',
        // but in a random order.
    }
}