Считывание выражений из файла - C#
Формулировка задачи:
То есть мы имеем некие выражения записанные в файле в виде строк:
5+3(4/5)*3.141
456/4(3.654+3)-3
и далее в подобном роде, как их считать так чтобы выражения считывались и соблюдался приоритет операций, т.е. сначала возведение в степень, потом умножение, деление, сложение и вычитание?
Решение задачи: «Считывание выражений из файла»
textual
Листинг программы
class Parser
{
string _input;
int _index;
private char Current => _input[_index];
public Parser(string input)
{
_input = input + "$";
}
public Complex Parse()
{
var result = ParseSum(1);
if (Current != '$')
throw new Exception();
return result;
}
public Complex ParseGroup()
{
if (!Match("("))
throw new Exception();
var result = ParseSum(1);
if (!Match(")"))
throw new Exception();
return result;
}
public Complex ParseSum(int sign)
{
var first = sign * ParseProduction(1);
int op = Match("+","-");
if (op == -1)
return first;
return first + ParseSum(op == 0 ? 1 : -1);
}
private Complex ParseProduction(int power)
{
Complex first;
if (Current == '(')
first = ParseGroup();
else if (char.IsDigit(Current) || Current == 'i')
first = ParseComplex();
else
throw new Exception();
first = Complex.Pow(first, power);
int op = Match("*", "/", "(");
if (op == -1)
return first;
if (op == 2)
_index--;
return (op == 0 || op == 2) ? first * ParseProduction(1) : first * ParseProduction(-1);
}
private Complex ParseComplex()
{
var sb = new StringBuilder();
while (char.IsDigit(Current) || Current == '.')
{
sb.Append(Current);
_index++;
}
var component = sb.Length > 0 ? double.Parse(sb.ToString(), System.Globalization.CultureInfo.InvariantCulture) : 1;
if (Match("i"))
return new Complex(0, component);
return new Complex(component, 0);
}
private int Match(params string[] words)
{
for (int i = 0; i < words.Length; i++)
if (Match(words[i]))
return i;
return -1;
}
private bool Match(string word)
{
if (word.Length > _input.Length - _index + 1)
return false;
bool matched = _input.Substring(_index, word.Length) == word;
if (matched)
_index += word.Length;
return matched;
}
}
static void Main()
{
var expression = "456/4(3.654+3)-3";
expression = expression.Replace(" ", "");
var parser = new Parser(expression);
var result = parser.Parse();
Console.WriteLine(result);
}