MathCalculators.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. namespace FMSAdmin.Helpers.Formula {
  8. public class MathCalculator {
  9. public enum Parameter {
  10. A = 0, B, C, D, E, F, G, H, I,
  11. J, K, L, M, N, O, P, Q, R,
  12. S, T, U, V, W, X, Y, Z
  13. }
  14. public enum OperatorType {
  15. Plus,
  16. Minus,
  17. Multiplication,
  18. Division,
  19. OpenBrace
  20. }
  21. public delegate decimal CalculateFunctionDelegate(decimal inputValue);
  22. public Dictionary<Parameter, MathParameterValue> Parameters = new Dictionary<Parameter, MathParameterValue>();
  23. public Dictionary<String, CalculateFunctionDelegate> Functions = new Dictionary<String, CalculateFunctionDelegate>();
  24. private List<String> OperationOrder = new List<string>();
  25. private static Regex doubleRegex = new Regex(@"^-?\d+(?:\.\d+)?", RegexOptions.Compiled);
  26. private static Regex functionRegex = new Regex(@"^\$(.+?)\((.)\)\$", RegexOptions.Compiled);
  27. private String Fomula { get; set; }
  28. Stack<FormulaItem> stack = new Stack<FormulaItem>();
  29. List<FormulaItem> CompliedFormula = new List<FormulaItem>();
  30. public void TracePostFormula() {
  31. foreach (var item in this.CompliedFormula) {
  32. }
  33. }
  34. public void SetParameter(MathParameterValue[] parameters) {
  35. foreach (var p in parameters) {
  36. this.Parameters.Add(p.Variable, p);
  37. }
  38. MapParameters();
  39. }
  40. public void SetFunction(string functionName, CalculateFunctionDelegate callback) {
  41. if (this.Functions.ContainsKey(functionName)) {
  42. this.Functions[functionName] = callback;
  43. return;
  44. }
  45. this.Functions.Add(functionName, callback);
  46. MapFunctions();
  47. }
  48. public List<FunctionItem> GetFunctions() {
  49. var list = new List<FunctionItem>();
  50. foreach (var item in this.CompliedFormula) {
  51. switch (item.Type) {
  52. case FormulaItem.ItemType.Function:
  53. list.Add((FunctionItem)item);
  54. break;
  55. }
  56. }
  57. return list;
  58. }
  59. private void MapFunctions() {
  60. foreach (var item in this.CompliedFormula) {
  61. switch (item.Type) {
  62. case FormulaItem.ItemType.Function:
  63. var f = item as FunctionItem;
  64. f.Function.FunctionDelegate = this.Functions[f.Function.FunctionName];
  65. break;
  66. }
  67. }
  68. }
  69. private void MapParameters() {
  70. foreach (var item in this.CompliedFormula) {
  71. switch (item.Type) {
  72. case FormulaItem.ItemType.OperandField:
  73. var o = item as OperandFieldItem;
  74. o.ParameterValue = this.Parameters[o.ParameterValue.Variable];
  75. break;
  76. case FormulaItem.ItemType.Function:
  77. var f = item as FunctionItem;
  78. switch (f.Value.Type) {
  79. case FormulaItem.ItemType.OperandField:
  80. var of = (OperandFieldItem)f.Value;
  81. of.ParameterValue = this.Parameters[of.ParameterValue.Variable];
  82. break;
  83. }
  84. break;
  85. }
  86. }
  87. }
  88. public decimal? Calculate() {
  89. Stack<FormulaItem> stack = new Stack<FormulaItem>();
  90. foreach (var item in this.CompliedFormula) {
  91. switch (item.Type) {
  92. case FormulaItem.ItemType.Constant:
  93. case FormulaItem.ItemType.OperandField:
  94. case FormulaItem.ItemType.Function:
  95. stack.Push(item);
  96. break;
  97. case FormulaItem.ItemType.Operator:
  98. var ci = this.CalculateOperator(stack.Pop(), stack.Pop(), ((OperatorItem)item).Operator);
  99. if (ci == null) {
  100. return null;
  101. }
  102. stack.Push(ci);
  103. break;
  104. }
  105. }
  106. return stack.Pop().GetValue();
  107. }
  108. private ConstantItem CalculateOperator(FormulaItem item1, FormulaItem item2, OperatorType op) {
  109. decimal result = 0;
  110. switch (op) {
  111. case OperatorType.Plus:
  112. result = item2.GetValue() + item1.GetValue();
  113. break;
  114. case OperatorType.Minus:
  115. result = item2.GetValue() - item1.GetValue();
  116. break;
  117. case OperatorType.Multiplication:
  118. result = item2.GetValue() * item1.GetValue();
  119. break;
  120. case OperatorType.Division:
  121. if (item1.GetValue() == 0)
  122. return null;
  123. result = item2.GetValue() / item1.GetValue();
  124. break;
  125. }
  126. return new ConstantItem { Value = result };
  127. }
  128. public bool Compile(string formula) {
  129. this.CompliedFormula.Clear();
  130. formula = formula.Replace(" ", "");
  131. Stack<OperatorItem> stack = new Stack<OperatorItem>();
  132. char[] braces = new char[] { '(', ')' };
  133. string operators = "+-*/";
  134. var array = formula.ToCharArray();
  135. int runcount = 0;
  136. for (var i = 0; i < array.Length;) {
  137. if (++runcount > 1000) break;
  138. var item = array[i];
  139. switch (item) {
  140. case '(':
  141. stack.Push(new OperatorItem { Operator = OperatorType.OpenBrace });
  142. i++;
  143. break;
  144. case ')':
  145. while (stack.Any()) {
  146. var stackItem = stack.Pop();
  147. if (stackItem.Operator == OperatorType.OpenBrace) {
  148. break;
  149. }
  150. CompliedFormula.Add(stackItem);
  151. }
  152. i++;
  153. break;
  154. case '$':
  155. Match funcMatch = functionRegex.Match(formula.Substring(i));
  156. if (funcMatch.Success == false || funcMatch.Groups.Count != 3) {
  157. CompliedFormula.Clear();
  158. return false;
  159. }
  160. var f = new FunctionItem {
  161. Function = new MathFunction { FunctionName = funcMatch.Groups[1].Value }
  162. };
  163. string value = funcMatch.Groups[2].Value;
  164. if ('A' <= value[0] && value[0] <= 'Z') {
  165. if (value.Length > 1) {
  166. return false;
  167. }
  168. f.Value = new OperandFieldItem { ParameterValue = new MathParameterValue { Variable = (Parameter)(value[0] - 'A') } };
  169. } else {
  170. decimal outputValue;
  171. if (decimal.TryParse(value, out outputValue) == false) {
  172. return false;
  173. }
  174. f.Value = new ConstantItem { Value = outputValue };
  175. }
  176. CompliedFormula.Add(f);
  177. i += funcMatch.Length;
  178. break;
  179. default:
  180. int operatorIndex = operators.IndexOf(item);
  181. bool isProcessed = false;
  182. if (operatorIndex == (int)OperatorType.Minus) {
  183. if (i == 0 || array[i - 1] == '(' || operators.IndexOf(array[i - 1]) >= 0) {
  184. isProcessed = true;
  185. }
  186. }
  187. if (isProcessed == false) {
  188. if (operatorIndex >= 0) {
  189. //if( operatorIndex < (int)OperatorType.Multiplication )
  190. {
  191. while (stack.Any()) {
  192. var stackItem = stack.Peek();
  193. if (stackItem.Operator == OperatorType.OpenBrace) break;
  194. if ((int)stackItem.Operator < operatorIndex) break;
  195. stack.Pop();
  196. CompliedFormula.Add(stackItem);
  197. }
  198. }
  199. stack.Push(new OperatorItem { Operator = (OperatorType)operatorIndex });
  200. i++;
  201. break;
  202. } else if ('A' <= item && item <= 'Z') {
  203. //Trace.WriteLine( item );
  204. CompliedFormula.Add(new OperandFieldItem { ParameterValue = new MathParameterValue { Variable = (Parameter)(item - 'A') } });
  205. i++;
  206. break;
  207. }
  208. }
  209. Match match = doubleRegex.Match(formula.Substring(i));
  210. if (match.Success == false) {
  211. throw new Exception("Error: Check Syntax : " + item);
  212. }
  213. decimal parseValue = decimal.Parse(match.Value);
  214. //Trace.WriteLine( value );
  215. CompliedFormula.Add(new ConstantItem { Value = parseValue });
  216. i += match.Value.Length;
  217. break;
  218. }
  219. }
  220. while (stack.Any()) {
  221. var operatorItem = stack.Pop();
  222. //Trace.WriteLine( operatorItem.Operator );
  223. CompliedFormula.Add(operatorItem);
  224. }
  225. return true;
  226. }
  227. public bool ExtractDouble(string inputValue, out decimal output) {
  228. return decimal.TryParse(inputValue, out output);
  229. }
  230. public abstract class FormulaItem {
  231. public enum ItemType {
  232. Operator,
  233. Constant,
  234. OperandField,
  235. Function
  236. }
  237. public ItemType Type { get; set; }
  238. public abstract decimal GetValue();
  239. }
  240. public class OperatorItem : FormulaItem {
  241. public OperatorType Operator { get; set; }
  242. public OperatorItem() {
  243. this.Type = FormulaItem.ItemType.Operator;
  244. }
  245. public override string ToString() {
  246. switch (this.Operator) {
  247. case OperatorType.Plus:
  248. return "+";
  249. case OperatorType.Minus:
  250. return "-";
  251. case OperatorType.Multiplication:
  252. return "*";
  253. case OperatorType.Division:
  254. return "/";
  255. }
  256. return "Unknown";
  257. }
  258. public override decimal GetValue() {
  259. throw new Exception("OperatorItem.GetValue() Called!");
  260. //return 0;
  261. }
  262. }
  263. public class ConstantItem : FormulaItem {
  264. public decimal Value { get; set; }
  265. public ConstantItem() {
  266. this.Type = FormulaItem.ItemType.Constant;
  267. }
  268. public override string ToString() {
  269. return this.Value.ToString();
  270. }
  271. public override decimal GetValue() {
  272. return this.Value;
  273. }
  274. }
  275. public class OperandFieldItem : FormulaItem {
  276. public MathParameterValue ParameterValue { get; set; }
  277. public OperandFieldItem() {
  278. this.Type = FormulaItem.ItemType.OperandField;
  279. }
  280. public override string ToString() {
  281. return this.ParameterValue.Variable.ToString();
  282. }
  283. public override decimal GetValue() {
  284. return this.ParameterValue.Value;
  285. }
  286. }
  287. public class FunctionItem : FormulaItem {
  288. public MathFunction Function { get; set; }
  289. public FormulaItem Value { get; set; }
  290. public FunctionItem() {
  291. this.Type = FormulaItem.ItemType.Function;
  292. }
  293. public override string ToString() {
  294. return string.Format("Function({0})", this.Value.GetValue());
  295. }
  296. public override decimal GetValue() {
  297. return this.Function.FunctionDelegate(this.Value.GetValue());
  298. }
  299. }
  300. }
  301. public class MathFunction {
  302. public String FunctionName { get; set; }
  303. public MathCalculator.CalculateFunctionDelegate FunctionDelegate { get; set; }
  304. }
  305. public class MathParameterValue {
  306. public MathCalculator.Parameter Variable { get; set; }
  307. public decimal Value { get; set; }
  308. }
  309. }