Write a C# library for delivery to external clients that can calculate the area of a circle from its radius and a triangle from three sides. In addition to performance, we evaluate:
Unit-tests Easy to add other shapes Calculate the area of a figure without knowing the type of figure in compile-time Checking if a triangle is a right triangle
-
Create
AreaCalculator
class instance -
Add custom formula by
AddFormula(string formulaName, string formula)
if needed -
Call
Calculate(string formulaName, double[] args)
methodAreaCalculator.AreaCalculator ac = new AreaCalculator.AreaCalculator(); ac.AddFormula("CircleByD", "{PI}*POW([d]/2,2)"); double[] r = ac.Calculate("CircleByD", new double[] { 10 });
- CircleByR. Calculates circle area by radius. Requires double[1] as input, where 0 element is radius. Returns double[1], where 0 element is area;
- TriangleBySides. Calculates triangle area by sides length. Requires double[3] as input, where 0,1,2 elements is triangle sides length. Returns double[2], where 0 element is area and 1 element is check for right triangle (0 is triangle, 1 is right triangle).
You may add custom formula by AddFormula(string formulaName, string formula)
method.
May use:
- Math functions, can be obtained by
MathFuncs
property. f.e.: SQRT() - Constants, in curly brackets, can be obtained by
Constants
property. f.e.: {PI} - Variables - one letter, in square brackets. f.e.: [x]
Also, you can combine several formulas into one by separating them with a comma. f.e. [A]+[B], [A]+[C] returns [A+B, A+C]
The results of the calculation will be returned in the corresponding elements of the output array.
- {PI} - Pi constant
- SQRT() - square root function. Using: SQRT[A] = square root of [A]
- POW() - power function. Using: POW[A, B] = a^b
- SIN() - sinus function. Using: SIN([A]) = sinus of [A], [A] in radians.
- COS() - cosinus function. Using: SIN([A]) = cosinus of [A], [A] in radians.
Also available:
+, -, *, /
&&, ||, !
>, <, >=, <=
==, !=
<condition>?<iftrue>:<iffalse>
You may add custom calculator by class that implements the ICalculateArea interface.
- Create class that implements ICalculateArea interface.
- Add variables as fields with
FormulaFieldAttribute
. Best pratice is use one capital letter for variable. - Assign elemens of args array to your fields in
CalculateArea
method. Note values in the args array correspond to the fields sorted alphabetically. - Write your calculator code in
CalculateArea
method. - Return double[] with your calculation results.
- Use
AddFormula(string formulaName, ICalculateArea calculator)
to add instance of your class as formula. - Call Calculate(string formulaName, double[] args)
Example of ICalculateArea implementation:
namespace AreaCalculator
{
public class QuadAreaCalculator : ICalculateArea
{
[FormulaField]
public double a;
[FormulaField]
public double b;
public double[] CalculateArea(double[] args)
{
a = args[0];
b = args[1];
return new[] { a * b };
}
}
}