コード例 #1
0
ファイル: main.cpp プロジェクト: abdiasfaw/RPNcalculator
string InfixToPostfix(string infix)
{
    stack<char> OPERATOR;
    string postfix;
    int i=0;
    while (i<infix.length())
    {
        if (infix[i]==' ' || infix[i]==',') {
            continue;
        }
        else if (IsOperator(infix[i]))
        {
            while(!OPERATOR.empty() && OPERATOR.peep() != '(' && HasHigherPrecedence(OPERATOR.peep(),infix[i]))
			{
				postfix+= OPERATOR.pop();
                postfix+=',';
			}
			OPERATOR.push(infix[i]);
        }
        else if (IsOperand(infix[i]) || infix[i]=='.')
        {
            postfix+=infix[i];
            while (IsOperand(infix[i+1]) || infix[i+1]=='.') {
                postfix+=infix[i+1];
                i++;
            }
            postfix+=',';
        }
        else if (infix[i] == '(')
		{
			OPERATOR.push(infix[i]);
		}
        else if(infix[i] == ')')
		{
			while(!OPERATOR.empty() && OPERATOR.peep() !=  '(')
            {
				postfix += OPERATOR.pop();
                postfix+=',';
			}
			OPERATOR.pop();
		}
        i++;
    }
    while(!OPERATOR.empty())
    {
		postfix += OPERATOR.pop();
	}
	return postfix;
}
コード例 #2
0
ファイル: ExpressionTree.C プロジェクト: sidpka/repo
TNode* CreateExpressionTree(char* exp){
int size=strlen(exp);
int i;
TNode* tmp1,*tmp2;
SNode* stack=NULL;

for(i=0;i<size;i++){
if(IsOperand(exp[i])){
tmp1=(TNode*)malloc(sizeof(TNode));
tmp1->data=exp[i];
tmp1->left=NULL;
tmp1->right=NULL;
Push(&stack,tmp1);
}else{
TNode* newNode=(TNode*)malloc(sizeof(TNode));

tmp1=Pop(&stack);
tmp2=Pop(&stack);

newNode->data=exp[i];
newNode->right=tmp1;
newNode->left=tmp2;
Push(&stack,newNode);
}
}
return Pop(&stack);
}
コード例 #3
0
ファイル: main.cpp プロジェクト: abdiasfaw/RPNcalculator
double postfixEvaluation(string pfix)
{
    stack<double> operand;
    double result;
    double op1,op2;
    int i=0;
    int j;
    while (i<pfix.length())
    {
        if (pfix[i]==',')
        {
            i++;
        }
        if (IsOperand(pfix[i]) || pfix[i]=='.')
        {
            j=1;
            result=(((double)pfix[i])-48);
            while (IsOperand(pfix[i+1]))
            {
                result*=10;
                result+=(((double)pfix[i+1])-48);
                i++;
            }
            if (pfix[i+1]=='.')
            {
                i++;
                while (IsOperand(pfix[i+1]))
                {
                    result+=(((double)pfix[i+1])-48)/(pow(10,j++));
                    i++;
                }
            }
            operand.push(result);
        }
        else if(IsOperator(pfix[i]))
        {
            op2=operand.pop();
            op1=operand.pop();
            result=evaluate(op1, pfix[i], op2);
            operand.push(result);
        }
        i++;
    }
    return operand.pop();
}
コード例 #4
0
ファイル: InfixToPostfix.C プロジェクト: sidpka/repo
void ConvertITP(char exp[]){

int i;
int len=strlen(exp);
Node* stack=(Node*)malloc(sizeof(Node));
stack->top=-1;
stack->capacity=len;
stack->Array=(int*)malloc(sizeof(int)*len);

for(i=0;i<len;i++){
    if(IsOperand(exp[i])){
    printf("%c",exp[i]);
    }

    else if(exp[i]=='('){
            Push(stack,exp[i]);
            }
    else if(exp[i]==')'){

    while(!IsStackEmpty(stack) && Peek(stack)!='('){
          printf("%c",Pop(stack));
          }
          if(!IsStackEmpty(stack) &&  Peek(stack)!='('){
             printf("\nError");
             return;
             }else{
             Pop(stack);
             }


    }
    else{

    while(!IsStackEmpty(stack) && Pref(exp[i])<=Pref(Peek(stack))){

    printf("%c",Pop(stack));

    }
    Push(stack,exp[i]);

    }


}

while(!IsStackEmpty(stack)){
printf("%c",Pop(stack));
}

}
コード例 #5
0
void Convert(char Infix[50], char Postfix[50])
   {
   stack OperatorStack;
   char TopSymbol, Symbol;
   int L;
   for (unsigned k = 0; k < strlen(Infix); k++)
      {
      Symbol = Infix[k];
      if (IsOperand(Symbol))
	  {
		 L=strlen(Postfix);
		 Postfix[L]=Symbol;
		 Postfix[L+1]='\0';
	  }
      else
         {
  while((OperatorStack.ptr)&&(TakesPrecedence(OperatorStack.top(), Symbol)) )
            {
            TopSymbol = OperatorStack.top();
            OperatorStack.pop();
		    L=strlen(Postfix);
		    Postfix[L]=TopSymbol;
		    Postfix[L+1]='\0';
            }
         if (( OperatorStack.ptr) && (Symbol == ')'))
            OperatorStack.pop();   // discard matching (
         else
            OperatorStack.push(Symbol);
         }
      }

	while ( OperatorStack.ptr)
      {
      TopSymbol = OperatorStack.top();
      OperatorStack.pop();
		 L=strlen(Postfix);
		 Postfix[L]=TopSymbol;
		 Postfix[L+1]='\0';
      }
   }
コード例 #6
0
ファイル: action.cpp プロジェクト: OasisGallagher/EL
Action* ActionParser::CreateAction(const std::string& cmd) {
	TextScanner scanner;
	scanner.SetText(cmd.c_str());

	char token[MAX_TOKEN_CHARACTERS];
	ScannerTokenType tokenType = scanner.GetToken(token);

	if (tokenType == ScannerTokenEndOfFile) {
		Debug::LogError("empty command");
		return nullptr;
	}

	Assert(tokenType == ScannerTokenIdentifier && strcmp(token, "$$") == 0, std::string("invalid left hand side operand: ") + token);

	tokenType = scanner.GetToken(token);
	Assert(tokenType == ScannerTokenAssign, "missing '='");

	tokenType = scanner.GetToken(token);
	Assert(tokenType == ScannerTokenIdentifier, "invalid command");

	Action* action = nullptr;
	Argument argument;

	if (IsOperand(token)) {
		int integer = 0;
		if (!Utility::ParseInteger(token + 1, &integer)) {
			Assert(false, std::string("invalid right operand ") + token);
		}
		else {
			action = new ActionIndex();
			argument.text = "identity";
			argument.parameters.push_back(integer);
		}
	}
	else {
		if (strcmp(token, "make") == 0) {
			action = new ActionMake();
			argument.text = "make";
		}
		else if (strcmp(token, "constant") == 0) {
			action = new ActionConstant();
			argument.text = "constant";
		}
		else if (strcmp(token, "symbol") == 0) {
			action = new ActionSymbol();
			argument.text = "symbol";
		}
		else if (strcmp(token, "literal") == 0) {
			action = new ActionLiteral();
			argument.text = "literal";
		}

		if (action != nullptr && !action->ParseParameters(scanner, argument)) {
			delete action;
			action = nullptr;
		}
	}

	Assert(action != nullptr, std::string("invalid action ") + token);
	action->SetArgument(argument);

	return action;
}
コード例 #7
0
bool ExpressionTree::SetInfixExpression(const char* inFix)
{       
    cout << "Infix:" << inFix << "\n";        
    vector<ItemTokenInfo>().swap(vecPostfixResult);
    //vecPostfixResult.shrink_to_fit();
                        
    CTokenParser parser;
    parser.PutExpression((char*)inFix);

    stack<ItemTokenInfo> opStack;
    string postFixString = "";    
    bool bErrorOccurred = false;

    while (1)
    {
        ItemTokenInfo token;
        memset(&token, 0x00, sizeof(token));
        if (!parser.GetToken(&token))
        {
            bErrorOccurred = true;
            break;
        }

        if (0 == token.nLength)
        {
            break;
        }

        #ifdef _DEBUG_MORE_
        cout << __LINE__ << ": token.nLength=" << token.nLength  << " token.nType=" << token.nType
             << " token.strTokenValue= " << token.strValue  <<  "\n";
        #endif
        
        if (IsUserFunction(&token))
        {
            opStack.push(token); //no precedence between functions 
        }
        else if (IsOperand(&token))
        {
            postFixString += " ";
            postFixString += token.strValue;
            vecPostfixResult.push_back(token);            
        }
        else if (IsOperator(&token))
        {
            while ( !opStack.empty() &&
                     LEFT_PARENTHESIS != opStack.top().nDetailedType && 
                     GetOperatorPrecedence(&opStack.top(), &token) <= 0 
                  )
            {                
                postFixString += " ";
                postFixString += opStack.top().strValue;
                vecPostfixResult.push_back(opStack.top());
                opStack.pop();                
            }
            opStack.push(token);            
        }
        else if (COMMA == token.nDetailedType && token.bThisTokenBelongsToTheUserFunctions ) // SumInt(1+1, 2)
        {
            while (!opStack.empty() &&
                    LEFT_PARENTHESIS != opStack.top().nDetailedType                     
                  )
            {
                postFixString += " ";
                postFixString += opStack.top().strValue;
                vecPostfixResult.push_back(opStack.top());
                opStack.pop();
            }           
        }
        else if (LEFT_PARENTHESIS == token.nDetailedType)
        {            
            opStack.push(token);
        }
        else if (RIGHT_PARENTHESIS == token.nDetailedType) 
        {
            //pop till starting '('
            while (!opStack.empty())
            {                
                if (LEFT_PARENTHESIS == opStack.top().nDetailedType)
                {
                    if (token.bThisTokenBelongsToTheUserFunctions)
                    {
                        //pop till starting function name 
                        opStack.pop(); 
                        
                        if (opStack.top().nDetailedType == LEFT_PARENTHESIS)
                        {
                            // (SumInt(1,1))
                            opStack.pop();
                        }
                        else
                        {
                            postFixString += " ";
                            postFixString += opStack.top().strValue; //function name
                            vecPostfixResult.push_back(opStack.top());
                            opStack.pop();
                        }
                        
                        break; 
                    }
                    else
                    {
                        opStack.pop();                         
                        break; 
                    }                    
                }
                postFixString += " ";
                postFixString += opStack.top().strValue;
                vecPostfixResult.push_back(opStack.top());
                                
                opStack.pop();
            }
        } //RIGHT_PARENTHESIS
    }

    if (bErrorOccurred)
    {
        return false;
    }

    while (!opStack.empty())
    {
        postFixString += " ";
        postFixString += opStack.top().strValue;

        vecPostfixResult.push_back(opStack.top());

        opStack.pop();        
    }

    cout << "Postfix is: " << postFixString << endl;
    
    return BuildExpressionTree();    
}
コード例 #8
0
bool ExpressionTree::BuildExpressionTree()
{    
    nDepthOfTree = 0;    
    DeleteExpressionTree(root_node);

    stack<expression_node*> treeNodeStack;
    stack<expression_node*> funcArgsNodeStack;

    for (vector<ItemTokenInfo>::iterator it = vecPostfixResult.begin(); it != vecPostfixResult.end(); ++it)
    {   
        //-------------------------------------------------------
        if (IsUserFunction(&(*it)))
        {            
            int nArgCnt = it->userFuncInfo.ntotalInputArgCnt;
                                    
            if (nArgCnt == 0)
            {
                expression_node* node = CreateTreeNode();
                expression_node* nodeEmptyR = CreateTreeNode(); //empty node
                expression_node* nodeEmptyL = CreateTreeNode(); //empty node   
                nodeEmptyR->nType = NODE_EMPTY;
                nodeEmptyL->nType = NODE_EMPTY;
                                
                node->right = nodeEmptyR;
                node->left = nodeEmptyL;
                
                node->nType = it->nType;
                node->nDetailedType = it->nDetailedType;
                node->expressionResult.nResultType = it->nType;
                node->expressionResult.nResultDetailedType = it->nDetailedType;

                memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo));
                treeNodeStack.push(node);
            }
            else if (nArgCnt == 1)
            {
                int nArgType = it->userFuncInfo.nFuncArgsTypes[0];
                if (treeNodeStack.empty()) //20140314
                {                    
                    cout << "ERROR : Wrong Expression!!\n";
                    return false;
                }
                expression_node* nodeStack = treeNodeStack.top(); 
                                
                if (FUNC_ARG_STR == nArgType)
                {
                    userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeStack->strVal);
                    userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeStack->expressionResult.strResult  );
                }
                
                treeNodeStack.pop();

                expression_node* nodeEmpty = CreateTreeNode(); //empty node   
                nodeEmpty->nType = NODE_EMPTY;
                expression_node* node = CreateTreeNode();                
                node->left = nodeStack ;
                node->right = nodeEmpty;
                
                node->nType = it->nType;
                node->nDetailedType = it->nDetailedType;
                node->expressionResult.nResultType = it->nType;
                node->expressionResult.nResultDetailedType = it->nDetailedType;
                
                memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo));
                treeNodeStack.push(node);
            }
            else if (nArgCnt == 2)
            {                
                int nArgType = it->userFuncInfo.nFuncArgsTypes[1];  // 1
                if (treeNodeStack.empty()) //20140314
                {
                    //Error!!!
                    cout << "ERROR : Wrong Expression!!\n";
                    return false;
                }
                expression_node* nodeArgR = treeNodeStack.top();
                
                if (FUNC_ARG_STR == nArgType)
                {
                    userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeArgR->strVal);
                    userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeArgR->expressionResult.strResult );
                }
                treeNodeStack.pop();

                nArgType = it->userFuncInfo.nFuncArgsTypes[0];  
                if (treeNodeStack.empty()) //20140314
                {
                    //Error!!!
                    cout << "ERROR : Wrong Expression!!\n";
                    return false;
                }
                expression_node* nodeArgL = treeNodeStack.top();                
                if (FUNC_ARG_STR == nArgType)
                {
                    userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeArgL->strVal);
                    userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeArgL->expressionResult.strResult );
                }                
                treeNodeStack.pop();
                
                expression_node* node = CreateTreeNode();
                node->right = nodeArgR; //스택에서 먼저 나온것이 오른쪽. 
                node->left = nodeArgL;
                
                node->nType = it->nType;
                node->nDetailedType = it->nDetailedType;
                node->expressionResult.nResultType = it->nType;
                node->expressionResult.nResultDetailedType = it->nDetailedType;

                memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo));
                treeNodeStack.push(node);
            }
            else if (nArgCnt > 2)
            {                                   
                expression_node* node = CreateTreeNode();   
                expression_node* nodeRight = NULL;
                                                
                for (int i = 0; i < nArgCnt; i++)
                {
                    int nArgType = it->userFuncInfo.nFuncArgsTypes[nArgCnt -i -1]; //args type XXX 
                    
                    //'1','2','3' 경우 '3','2',1' 순서로 pop
                    //         StrCat3 
                    //   '1'             '2','3'

                    if (i == nArgCnt - 1) // last pop -> left
                    {                        
                        if (treeNodeStack.empty()) //20140314
                        {
                            //Error!!!
                            cout << "ERROR : Wrong Expression!!\n";
                            return false;
                        }
                        expression_node* nodeLeft = treeNodeStack.top();
                        treeNodeStack.pop();                        
                        if (FUNC_ARG_STR == nArgType)
                        {
                            userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeLeft->strVal);
                            userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeLeft->expressionResult.strResult );
                        }
                        node->left = nodeLeft;
                    }
                    else if (i == nArgCnt - 2) // right
                    {                    
                        if (treeNodeStack.empty()) //20140314
                        {
                            //Error!!!
                            cout << "ERROR : Wrong Expression!!\n";
                            return false;
                        }
                        nodeRight = treeNodeStack.top();
                        treeNodeStack.pop();                        
                        if (FUNC_ARG_STR == nArgType)
                        {
                            userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeRight->strVal);
                            userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeRight->expressionResult.strResult );
                        }
                    }
                    else
                    {
                        if (treeNodeStack.empty()) //20140314
                        {
                            //Error!!!
                            cout << "ERROR : Wrong Expression!!\n";
                            return false;
                        }
                        expression_node* nodeForMore2Args = treeNodeStack.top();
                        treeNodeStack.pop();                        
                        if (FUNC_ARG_STR == nArgType)
                        {
                            userFuncs.GetStringSingleQuotationsBothSidesRemoved(nodeForMore2Args->strVal);
                            userFuncs.GetStringSingleQuotationsBothSidesRemoved ( nodeForMore2Args->expressionResult.strResult );
                        }
                        funcArgsNodeStack.push(nodeForMore2Args);
                    }
                   
                }//for
                                
                expression_node* nodePosForFuncArgs = NULL;
                while (!funcArgsNodeStack.empty() ) 
                {
                    if (nodePosForFuncArgs == NULL)
                    {
                        nodePosForFuncArgs = nodeRight->rightSiblingForMore2funcArgs = funcArgsNodeStack.top();
                    }
                    else
                    {
                        nodePosForFuncArgs->rightSiblingForMore2funcArgs = CreateTreeNode();
                        nodePosForFuncArgs->rightSiblingForMore2funcArgs = funcArgsNodeStack.top();
                        nodePosForFuncArgs = nodePosForFuncArgs->rightSiblingForMore2funcArgs;
                    }

                    funcArgsNodeStack.pop();
                }
                                
                node->right = nodeRight;
                
                node->nType = it->nType;
                node->nDetailedType = it->nDetailedType;
                node->expressionResult.nResultType = it->nType;
                node->expressionResult.nResultDetailedType = it->nDetailedType;

                memcpy(&node->userFuncInfo, &it->userFuncInfo, sizeof(node->userFuncInfo));
                treeNodeStack.push(node);
                
            }   
        }
        //-------------------------------------------------------
        else if (IsOperand(&(*it)))
        {
            expression_node* node = CreateTreeNode();
            
            if (NODE_NUMBER == it->nType)
            {                
                if (NUMBER_LONG == it->nDetailedType)
                {
                    node-> nLongValue = atol(it->strValue);
                    node->expressionResult.nResultLong = node->nLongValue;
                }
                else if (NUMBER_FLOAT == it->nDetailedType)
                {
                    node-> nFloatValue = (float)atof(it->strValue);
                    node->expressionResult.nResultFloat = node->nFloatValue;
                }
                else
                {
                    cout << "Error \n";                    
                }                
            }
            else 
            {
                memcpy(&node->strVal, it->strValue, sizeof(node->strVal));
                memcpy ( &node->expressionResult.strResult, it->strValue, sizeof( node->expressionResult.strResult ) );
            }
            
            node->nType = it->nType;
            node->nDetailedType = it->nDetailedType;
            node->expressionResult.nResultType = it->nType;
            node->expressionResult.nResultDetailedType = it->nDetailedType;
                        
            treeNodeStack.push(node);
        }
        //-------------------------------------------------------
        else if (IsOperator(&(*it)))
        {
            if (treeNodeStack.empty()) //2-14-314
            {                
                return false;
            }
            
            expression_node* node1 = treeNodeStack.top();
            treeNodeStack.pop();

            if (treeNodeStack.empty()) //2-14-314
            {                
                return false;
            }

            expression_node* node2 = treeNodeStack.top();
            treeNodeStack.pop();

            expression_node* node = CreateTreeNode();
            node->right = node1;  
            node->left = node2;

            node->nType = it->nType;
            node->nDetailedType = it->nDetailedType;
            node->expressionResult.nResultType = it->nType;
            node->expressionResult.nResultDetailedType = it->nDetailedType;

            treeNodeStack.push(node);
        }
        else
        {
            cout << "-- Not Operator/Operand" << "\n";
        }
    }

    if (treeNodeStack.empty()) //20140314
    {        
        cout << "ERROR : Wrong Expression!!\n";
        return false;
    }
    root_node = treeNodeStack.top();
    treeNodeStack.pop();

    return true;
}
コード例 #9
0
ファイル: bakupexpressionTree.c プロジェクト: elainels/LALG
PNode CreateInfixTree(char* exp)
{
   // create a dummy root with minimal precedence
   // its content is trivial
   PNode root = CreateNode("0");
   root->precedence = 0;

   // the previous operand of current operator
   PNode preOperand = NULL;
   // the previous operator of current operator
   PNode preOperator = root;
   // the impact of preceding parenthesis, if any
   int correction = 0;
	int i = 0;

	char* token = strtok( exp, " " );
	
	while(token)
	{
      if (IsOperand(token))
      {
         preOperand = CreateNode(token);
      }
      else if (IsOperator(token))
      {
	  	printf("entrou em eh operador\n");
         PNode p = CreateNode(token);
         p->precedence = GetPrecedence(token) + correction;
         if (p->precedence > preOperator->precedence)
         {
            p->left = preOperand;
            preOperator->right = p;
            p->parent = preOperator;
         }
         else
         {
            preOperator->right = preOperand;
            PNode q = preOperator->parent;
            while (p->precedence <= q->precedence) q = q->parent;

            p->left = q->right;
            q->right = p;
            p->parent = q;
         }
         preOperand = NULL;
         preOperator = p;

      }//else if (IsOperator(exp[i])
      else if (IsLeftParenthesis(token))
      {
         correction += 2;
      }
      else if (IsRightParenthesis(token))
      {
         correction -= 2;
      }
      else
      {
         printf("illegal token found: %c\n", exp[i]);
         break;
      }

	  token = strtok(NULL, " ");
   }//while

   if (preOperand == NULL)
       printf("illegal expression: cannot end with operator: %s\n", preOperator->data);
   else preOperator->right = preOperand;

   // delete dummy root
   PNode realRoot = root->right;
   //delete root;
   free(root);
   if (realRoot) realRoot->parent = NULL;
   return realRoot;
}