View Single Post
  #1  
Old 09-03-2010, 12:19 PM
--BulletMagnet-- is offline --BulletMagnet--
--BulletMagnet--'s Avatar
DF2 Forever

Join Date: Jun 2005
Location: USA
Posts: 718

Send a message via MSN to --BulletMagnet--
C#: Factorials, Combinations, and Permutations Class

Code:
    // Class Name: Basic Counting Theory
    // Author: Bullet Magnet
    // Version: 1.0
    // Copyright: 2010 Bullet Magnet

    public class BasicCountingTheory
    {
        #region CaclulateFactorial
        // Factorial method
        // Accepts one parameter of type long
        public static long CalculateFactorial(long x)
        {
            long fact = 1; 
            long i = 1; // Lowest possible term in a factorial

            // Loop through each subsequent terms of x
            while (i <= x)
            {
                fact = fact * i; 
                i++;
            }
            return fact;
        }
        #endregion

        #region Permutation
        // This method calculates permutations, in which the order of a selection matters
        // Accepts 2 parameters for use in the main formula
        public static long Permutation(long a, long b)  
        {
            // Variable used to store result
            long result;
            // Main formula: (n!/((n-r)!))
            result = ((CalculateFactorial(a))/(CalculateFactorial(a-b)));

            return result;
        }
        #endregion

        #region Combination(long a, long b)
        // This method calclulates combinations, in which order of a selection doesn't matter
        public static long Combination(long a, long b)
        {
            // Variable used to store result
            long result;
            // Main formula: (n!/((n-r)!)r!)
            result = ((CalculateFactorial(a)) / ((CalculateFactorial(a - b) * CalculateFactorial(b))));

            return result;
        }
        #endregion
    }
Reply With Quote