Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutation and Combination in C# [closed]

Tags:

c#

math

Please tell me how can I apply permutation and combination in C# console application and take values of N and r and calculate permutation and combination.

like image 860
sikrigagan Avatar asked Oct 11 '14 06:10

sikrigagan


1 Answers

I just had a go doing this for fun, it's actually a little challenging as a naive implementation overflows long very quickly. I've included those in comments.

Equations

nPr = n! / (n - r)!
nCr = n! / r! (n - r)!

Implementaion

public static class PermutationsAndCombinations
{
    public static long nCr(int n, int r)
    {
        // naive: return Factorial(n) / (Factorial(r) * Factorial(n - r));
        return nPr(n, r) / Factorial(r);
    }

    public static long nPr(int n, int r)
    {
        // naive: return Factorial(n) / Factorial(n - r);
        return FactorialDivision(n, n - r);
    }

    private static long FactorialDivision(int topFactorial, int divisorFactorial)
    {
        long result = 1;
        for (int i = topFactorial; i > divisorFactorial; i--)
            result *= i;
        return result;
    }

    private static long Factorial(int i)
    {
        if (i <= 1)
            return 1;
        return i * Factorial(i - 1);
    }
}

Usage

Console.WriteLine(PermutationsAndCombinations.nPr(10, 3));
Console.WriteLine(PermutationsAndCombinations.nCr(10, 3));

Prints:

720
120
like image 105
weston Avatar answered Oct 23 '22 07:10

weston