24 game/CSharp: Difference between revisions
Content added Content deleted
mNo edit summary |
m (removed some duplication caused by copy/paste, edited intro text, homogenized open bracket placement) |
||
Line 4: | Line 4: | ||
You could, for example, use the CodeDOM to dynamically compile an object that contains the expression string. |
You could, for example, use the CodeDOM to dynamically compile an object that contains the expression string. |
||
Or, while not necessarily a good coding practice, but certainly a short and simple route, you could use System.Xml.XPath.XPathNavigator.Evaluate(string xpath) as shown here: |
|||
<lang csharp> |
<lang csharp> |
||
public class XPathEval : I24MathParser { |
public class XPathEval : I24MathParser { |
||
Line 33: | Line 33: | ||
Here is a more verbose, native solution - a lightweight math expression parser for evaluating 24 Game user input: |
Here is a more verbose, native solution - a lightweight math expression parser for evaluating 24 Game user input: |
||
<lang csharp> |
<lang csharp> |
||
/// <summary> |
|||
/// Lightweight math parser - C# does not have an Evaluate function |
|||
/// </summary> |
|||
public class MathParser : I24MathParser { |
|||
/// <summary> |
/// <summary> |
||
/// Lightweight math parser - C# does not have an Evaluate function |
/// Lightweight math parser - C# does not have an Evaluate function |
||
Line 77: | Line 73: | ||
float Solve(string equation){ |
float Solve(string equation) { |
||
//carry out order of operations |
//carry out order of operations |
||
// bracketed subexpressions - for any operator |
// bracketed subexpressions - for any operator |
||
Line 96: | Line 92: | ||
Match match = subExpression.Match(equation); |
Match match = subExpression.Match(equation); |
||
while (match.Success) |
while (match.Success) { |
||
⚫ | |||
{ |
|||
⚫ | |||
{ |
|||
//recursively solve for subexpressions -- match group 1 excludes outer brackets |
//recursively solve for subexpressions -- match group 1 excludes outer brackets |
||
subResult = Solve(match.Groups[1].Value); |
subResult = Solve(match.Groups[1].Value); |
||
} |
} |
||
else |
else { |
||
{ |
|||
//no more nested expressions - get final result for this subExpression |
//no more nested expressions - get final result for this subExpression |
||
subResult = ParseEquation(match.Value); |
subResult = ParseEquation(match.Value); |