Cod sursa(job #2088778)

Utilizator llalexandruLungu Alexandru Ioan llalexandru Data 15 decembrie 2017 20:36:40
Problema Evaluarea unei expresii Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>

using namespace std;

const string Functii[] = {"abs", "cos", "sin", "tan"};
const char Operatii[] = {'+', '-', '*', '/'};
const int nrfunctii = 4, nroperatii=4;

struct nod {
	int val = 0;
	string sp = "";
	nod* op1;
	nod* op2;
};

nod* Evaluare(string exp);
void ScrieReguli();
int GetValue(nod* act);

int main()
{
	string exp;
	freopen("evaluare.in", "r", stdin);
	freopen("evaluare.out", "w", stdout);
	//ScrieReguli();
	//cout << "Introduce-ti expresia: ";
	cin >> exp;
	nod* start = Evaluare(exp);
	cout << GetValue(start) << '\n';
    return 0;
}

void ScrieReguli()
{
	char line[200];
	ifstream fin("reguli.txt");
	while (fin.getline(line, 200))
		cout << line << '\n';
}

int SearchFunction(string exp, int s, int d)
{
	for (int i = 0; i < nrfunctii; i++)
		if (exp.find(Functii[i]))
			return exp.find(Functii[i]);
}

int StrToDouble(string exp)
{
	int x=0;
	for (int i = 0; i < exp.size(); i++)
		x = x * 10 + exp[i] - '0';
	return x;
}

bool FirstAndLastPar(string exp)
{
	int P[10000], last = 0;;
	for (int i = 0; i < exp.size()-1; i++)
		if (exp[i] == '(')
			P[last++] = i;
		else if (exp[i] == ')')
			last--;
	if (exp[exp.size() - 1] == ')' && P[0] == 0)
		return 1;
	return 0;
}

nod* Evaluare(string exp)
{
	//SearchFunction(exp, s, d);
	nod* op = new nod();
	int last = 0, Wh[10000], nr = 0;
	char Op[10000];

	if (exp == "")
	{
		op->val = 0;
		return op;
	}

	if (FirstAndLastPar(exp))
		return Evaluare(exp.substr(1, exp.size()-2));

	for (int i = 0; i < exp.size(); i++)
		if (exp[i] == '(')
			last++;
		else if (exp[i] == ')')
			last--;
		else if (last==0)
			for (int j = 0; j < nroperatii; j++)
				if (exp[i] == Operatii[j])
				{
					Op[nr] = exp[i];
					Wh[nr++] = i;
					break;
				}

	for (int j = 0; j < nroperatii; j++)
		for (int i = 0; i < nr; i++)
			if (Op[i]==Operatii[j])
			{
				op->sp = Operatii[j];
				op->op1 = Evaluare(exp.substr(0, Wh[i]));
				op->op2 = Evaluare(exp.substr(Wh[i] + 1, string::npos));
				return op;
			}
	op->val = StrToDouble(exp);
	return op;
}

int GetValue(nod* act)
{
	if (act->sp != "")
	{
		if (act->sp == "+")
			return GetValue(act->op1) + GetValue(act->op2);
		if (act->sp == "-")
			return GetValue(act->op1) - GetValue(act->op2);
		if (act->sp == "*")
			return GetValue(act->op1) * GetValue(act->op2);
		if (act->sp == "/")
			return GetValue(act->op1) / GetValue(act->op2);
	}
	else
		return act->val;
}