package br.hellokeita.utils
{
/**
* @author keita (keita.kun at gmail.com)
* @svn http://code.hellokeita.in/public
* @url http://labs.hellokeita.com/
*
* The MathUtils class is bunch of mathematical methods.
*/
public class MathUtils
{
/**
* Solve combinations
*
* Passing 2 parameters n and k it calculates the combination defined by (n!) / (k! * (n - k)!)
*
* @param number of objects from which you can choose
* @param number to be chosen
*
* @return number of combination
*
* @see http://en.wikipedia.org/wiki/Combination
*/
static public function combination(a:uint, b:uint):uint {
if (a == b) return 1;
if (b == 0) return 1;
if (a < b) return 1;
var d:uint = a - b;
var s:uint;
if (d > b) {
s = d + 1;
d = 1 / factorial(b);
}else {
s = b + 1;
d = 1 / factorial(d);
}
return factorial(a, s) * d;
}
/**
* Calculates factorial
*
* Calculates the factorial of a number.
* Also, passing the start value you can choose the range of the factorial, useful to solve combination()
*
* @param number of factorial
* @param [optional] start number for the factorial
*
* @return product of each positive integer value between start to value
*
* @see http://en.wikipedia.org/wiki/Factorial
*/
static public function factorial(value:uint, start:uint = 1):uint {
if (start > value) return 0;
if (value == start) return value;
var r:uint = 1;
for (var i:uint = start; i <= value; i++) {
r *= i;
}
return r;
}
/**
* Solve equation system using Cramer's rule
*
* Solves an equation system using Cramer's rule.
*
* @example
Having 2 equation with 2 unknown values such as 3 ~~ a + 1 ~~ b = 3 and 5 ~~ a - 2 ~~ b = 20