Beispiel #1
0
void InfixToPostfix::convert()
{
    char Y[50],val;
    int l=strlen(X),len=0,pr,pr1;
    push('(');
    X[l]=')';
    for(int i=0;i<=l;i++)
    {
        if(isalnum(X[i]))
        {
            Y[len]=X[i];
            len++;
        }
        else if(X[i]=='(')
            push(X[i]);
        else if(X[i]=='^'||X[i]=='/'||X[i]=='*'||X[i]=='+'||X[i]=='-')
        {
            pr=checkPrecedence(X[i]);
            pr1=checkPrecedence(stack[top]);
            while(pr1>pr||pr1==pr)
            {
                val=pop();
                Y[len]=val;
                len++;
                pr1=checkPrecedence(stack[top]);
            }
            push(X[i]);
        }
        else if(X[i]==')')
        {
            while(stack[top]!='(')
            {
                val=pop();
                Y[len]=val;
                len++;
            }
            pop();
        }
    }
    Y[len]='\0';
    cout<<Y;
}
Beispiel #2
0
int compareTwoOper(char n)
{
    if(checkPrecedence(n) == checkPrecedence(stack[top]) || checkPrecedence(n) < checkPrecedence(stack[top]))
        return 0;
    if(checkPrecedence(n) > checkPrecedence(stack[top]))
        return 1;
}
Beispiel #3
0
int main(int argc, char** argv){


    /*main expression is one string of all args put together*/
  char* mainExpression = getExpressionFromArgs(argc, argv);

    /*list of tokens*/
  tokenNode *mainList = malloc(sizeof(tokenNode));

    /*not useful yet
     *TODO: Something with variables*/
  int totalVariables = 0;

    /*keep iterating i until it reaches a ; in main expression*/
  for(int i = 0; mainExpression[i] != ';'; i++){

      /*get necesarry tokens from expression*/

    if(isalpha(mainExpression[i])){
      addTokenToList(mainList, getVariableLexeme(mainExpression, &i));      
    }
    if(isdigit(mainExpression[i] )){
      addTokenToList(mainList, getNumericLexeme(mainExpression, &i));      
    }
    if(isOperator(mainExpression[i])){
      addTokenToList(mainList, getOperatorLexeme(mainExpression, &i));      
    }
    if(mainExpression[i] == '$'){
      addTokenToList(mainList, getSpecialLexeme(mainExpression, &i));      
    }
  }
  
    /*conductor is the iterator to move across the list*/
  tokenNode *conductor;
    /*tempNode is used for freeing memory*/
  tokenNode *tempNode;
    /*used to determine if there are anymore
     *RELEVANT operators to compute with */
  _Bool noMoreOperators = false;

    /*check if we have one number left over*/
  while(mainList->size > 1){  

      /*i represents the current order of precedence to be checked,
       *in EMDAS order*/
    for(int i = 0; i < 3; i++){    
        /*set/reset conductor back to start of list*/
      conductor = mainList;

        /*set/reset noMoreOperators so that next loop can continue*/
      noMoreOperators = false;
      while(!noMoreOperators){           
          /*default; if the list is traversed and there are no more operators, loop will end
           *this was inspired by traditional bubble sort*/
        noMoreOperators = true;

          /*while not at end of list*/
        while(conductor->next != NULL){                          

            /*check if the next token is an operator*/            
          if(conductor->next->value.type == operator){
              /*check if the operator token is the same precedence as the operator we are looking for*/              
            if(checkPrecedence(conductor->next->value) == i){              
                /*if so, we have found a RELEVANT operator and noMoreOperators is false*/
              noMoreOperators = false;
                /*perform necesarry calculation depending on current precedence (i)*/            
              switch(getOperatorID(conductor->next->value)){
                case 0:                

                    /*set conductor value to conductor^conductor->next->next*/
                  conductor->value = tokenExponentation(conductor->value, conductor->next->next->value);
                    /*set tempNode to the 3 items down the list (next number)*/                  
                  tempNode = conductor->next->next->next;
                    /*free the nodes between current node (conductor) and tempNode (conductor->next->next->next)*/
                  free(conductor->next);
                  free(conductor->next->next);

                    /*link conductor with tempNode*/
                  conductor->next = tempNode;
                    /*subtract two tokens from mainList*/
                  mainList->size -= 2;

                  break;
                case 1:
                    /*set conductor value to conductor*conductor->next->next*/
                  conductor->value = tokenMultiplication(conductor->value, conductor->next->next->value);
                    /*set tempNode to the 3 items down the list (next number)*/                  
                  tempNode = conductor->next->next->next;
                    /*free the nodes between current node (conductor) and tempNode (conductor->next->next->next)*/
                  free(conductor->next);                  
                  free(conductor->next->next);

                    /*link conductor with tempNode*/
                  conductor->next = tempNode;

                    /*subtract two tokens from mainList*/
                  mainList->size -= 2;

                  break;
                case 2:
                    /*set conductor value to conductor/conductor->next->next*/
                  conductor->value = tokenDivision(conductor->value, conductor->next->next->value);
                    /*set tempNode to the 3 items down the list (next number)*/                  
                  tempNode = conductor->next->next->next;
                    /*free the nodes between current node (conductor) and tempNode (conductor->next->next->next)*/
                  free(conductor->next);                  
                  free(conductor->next->next);

                    /*link conductor with tempNode*/
                  conductor->next = tempNode;

                    /*subtract two tokens from mainList*/
                  mainList->size -= 2;

                  break;
                case 3:
                    /*set conductor value to conductor+conductor->next->next*/
                  conductor->value = tokenAddition(conductor->value, conductor->next->next->value);
                    /*set tempNode to the 3 items down the list (next number)*/                  
                  tempNode = conductor->next->next->next;
                    /*free the nodes between current node (conductor) and tempNode (conductor->next->next->next)*/
                  free(conductor->next);                  
                  free(conductor->next->next);

                    /*link conductor with tempNode*/
                  conductor->next = tempNode;

                    /*subtract two tokens from mainList*/
                  mainList->size -= 2;          

                  break;
                case 4:
                    /*set conductor value to conductor-conductor->next->next*/
                  conductor->value = tokenSubtraction(conductor->value, conductor->next->next->value);
                    /*set tempNode to the 3 items down the list (next number)*/                  
                  tempNode = conductor->next->next->next;
                    /*free the nodes between current node (conductor) and tempNode (conductor->next->next->next)*/
                  free(conductor->next);                  
                  free(conductor->next->next);

                    /*link conductor with tempNode*/
                  conductor->next = tempNode;

                    /*subtract two tokens from mainList*/
                  mainList->size -= 2;          

                  break;
                default:
                    /*if current token is not really a token*/
                  printf(ANSI_COLOR_MAGENTA"Error: Erroneous token: %s\n"ANSI_COLOR_RESET, conductor->next->value.lexeme);
                  exit(1);

              }

                /*show your work!*/
              for(int j = 0; j < mainList->size; j++){
                printf("%s", getTokenFromList(mainList, j).lexeme);
              }
              printf("\n");              
            }
          }
            /*iterate down the list unless at end of list,
            unless the current operator is of the desired precedence
            this is to avoid skipping operators on accident*/          
          if(conductor->next != NULL  && checkPrecedence(conductor->next->value) != i){            
            conductor = conductor->next;            
          }
        }
      }          
    }
  }
    /*print list*/
  printf("Answer: %s\n",getTokenFromList(mainList, 0).lexeme);

}
/*
* Prototype: int parseExpression(const std::string&)

* What: This method converts the expression (entered in postfix notation) to prefix notation, Reverse Polish Notation (RPN).

* How to Call: This method is called in the main function in the test file.
ex: Calculator myCalc; std::string myExpression; myCalc.parseExpression(myExpression);

* Pre-Conditions:
- A Calculator object must have been built.
- User must pass in an expression.

* Post-Conditions:
- Expression will be parsed into RPN and stored in the member container: Queue<std::string> output
- Will call the function evaluateExpression() and return an int to either signify a successful calculation, or and error (e.g., division by zero, mismatched parentheses, etc.).
*/
int Calculator::parseExpression(std::string& expression)
{
	expression = checkForUnaryMinus(expression);
	for (size_t i = 0; i < expression.length(); i++)
	{
		const std::string token = expression.substr(i, 1);

		if (token == " ") // If space, skip iteration and throw it out.
			continue;

		else if (token == "u")
		{
			std::string newToken = "-";
			i++; // Skip over the u
			while (i < expression.length() && !isOperator(expression.substr(i, 1)) && !isParenthesis(expression.substr(i, 1)))
				newToken.append(expression.substr(i++, 1));
			i--; // For loop will increment i, causing it to skip over operators and such, so decrement i here
			output.enqueue(newToken);
		}

		else if (isOperator(token))
		{
			if (!operators.empty())
			{
				std::string op2 = operators.top();

				while (isOperator(op2) && ((isLeftAssoc(token) && checkPrecedence(token, op2) == 1) || (checkPrecedence(token, op2) == 0)))
				{
					output.enqueue(op2);
					operators.pop();

					if (!operators.empty())
						op2 = operators.top();
					else
						break;
				}
			}
			operators.push(token);
		}

		else if (isParenthesis(token))
		{
			if (token == "(")
				operators.push(token);
			else
			{
				if (!operators.empty())
				{
					std::string top = operators.top();

					while (top != "(")
					{
						output.enqueue(top);
						operators.pop();
						if (operators.empty())
							break; // Mismatched Parentheses

						top = operators.top();
					}

					if (!operators.empty()) // You've found the left parenthesis!
						operators.pop();
					if (top != "(")
						return 1; // Mismatched Parentheses
				}
			}
		}

		else if (isNumber(token))
		{
			std::string newToken;
			while (i < expression.length() && !isOperator(expression.substr(i, 1)) && !isParenthesis(expression.substr(i, 1)))
				newToken.append(expression.substr(i++, 1));
			i--; // For loop will increment i, causing it to skip over operators and such, so decrement i here
			output.enqueue(newToken);
		}

		else
			return 5; // Invalid character
	}

	while (!operators.empty())
	{
		std::string top = operators.top();

		if (isParenthesis(top))
			return 1; // Mismatched Parentheses

		output.enqueue(top);
		operators.pop();
	}

	return (evaluateExpression());
}
Beispiel #5
0
int buildTree(command_t commList, int i, int rootListIndex, int* rootList)
{
	int maxOperandSize = 100;
	int maxOperatorSize = 100;
	int operandIndex = 0; // first empty index in operand stack
	int operatorIndex = 0; // first empty index in operator stack
	//printf("rootListIndex: %d\n", rootListIndex);

	int* operatorList = malloc(sizeof(int)*maxOperatorSize);
	int* operandList = malloc(sizeof(int)*maxOperandSize);
	int returnIndex = -1;
	//int i;
	//printf("# of commands: %d\n", g_commandListLength);
	for(; i < g_commandListLength; i++)
	{
	//	printf("ii: %d\n", i);
		//printf("p..operatorIndex: %d\n", operatorIndex);
		//printf("p..operandIndex: %d\n", operandIndex);
		if(operandIndex == maxOperandSize)
		{
			maxOperandSize *= 2;
			operandList = realloc(operandList, sizeof(int)*maxOperandSize);
		}
		else if(operatorIndex == maxOperatorSize)
		{
			maxOperatorSize *= 2;
			operatorList = realloc(operatorList, sizeof(int)*maxOperatorSize);
		}

		else if(commList[i].type == SIMPLE_COMMAND)
		{
			//printf("simple command\n");
			//printf("operandIndex: %d\n", operandIndex);
			operandList[operandIndex] = i;
			operandIndex++;
		//	printStack(operatorIndex-1, operandIndex-1, operatorList, operandList);
			
			continue;
		}

		else if(commList[i].type == OPEN_PAREN)
		{
			// push onto operator stack
			operatorList[operatorIndex] = i;
			operatorIndex++;
			continue;
		}
		else if(commList[i].type == CLOSED_PAREN)
		{
			// pop off until reach open paren
			int topIndex = operatorList[operatorIndex-1];
			enum command_type top = commList[topIndex].type-1;
			while(top != OPEN_PAREN)
			{
				//printf("pop til open paren \n");
				popOperator(operatorIndex-1, operandIndex-1, operatorList, operandList, commList);
				operandIndex--;
				operatorIndex--;
				//printStack(operatorIndex-1, operandIndex-1, operatorList, operandList);
				// print stack for debugging
				//printf("topIndex: %d\n", topIndex);
				topIndex = operatorList[operatorIndex-1];
				top = commList[topIndex].type;
			}
			//end loop: top = OPEN_PAREN
			//printf("end paren popping\n");
			int subShellIndex = operatorList[operatorIndex-1];
			setSubShell(subShellIndex, operandIndex-1, operandList, commList);
			operatorIndex--;
			//printCommandList(commList, g_commandListLength);
			//printStack(operatorIndex-1, operandIndex-1, operatorList, operandList);

			continue;
		}
		else if(commList[i].type == NEW_LINE)
		{
			returnIndex = i;
			if(i+1 == g_commandListLength)
			{
			//	printf("return\n");
				returnIndex = -1;
			}
			break;
		}
		else if(commList[i].type == IGNORE_COMMAND)
		{
			continue;
		}
		/*else if(commList[i].type == SEQUENCE_COMMAND)
		{
			//printf("i: %d\n", i);
			returnIndex = i;
			if(i == g_commandListLength-2 && commList[i+1].type == NEW_LINE)
			{
				returnIndex = -1;
			}
			break;
		}*/
		else
		{
			enum command_type input = commList[i].type;
			if(operatorIndex == 0)
			{
				operatorList[0] = i;
				operatorIndex++;
				//printStack(operatorIndex-1, operandIndex-1, operatorList, operandList);
				continue;
			}
			
			int topIndex = operatorIndex-1;
			enum command_type top = commList[operatorList[topIndex]].type;

		/*	printf("topIndex: %d\n", topIndex);
			printf("top: ");
			printCommandType(top);
			printf("input: ");
			printCommandType(input);*/

			while(checkPrecedence(input, top) && operatorIndex > 0)
			{
			//	printf("PRECEDENCE\n");
			//	printf("stack1:\n");
				//printStack(operatorIndex-1, operandIndex-1, operatorList, operandList);
				popOperator(operatorIndex-1, operandIndex-1, operatorList, operandList, commList);
				operandIndex--;
				operatorIndex--;
			//	printf("stack2:\n");
				//printStack(operatorIndex-1, operandIndex-1, operatorList, operandList);

				//printf("op index: %d\n", operatorIndex);
				// print stack for debugging
				topIndex = operatorList[operatorIndex-1];
				top = commList[topIndex].type;
			/*	printf("in loop topIndex: %d\n", topIndex);
				printf("in loop top: ");
				printCommandType(top);
				printf("in loop input: ");
				printCommandType(input);*/
			}


			operatorList[operatorIndex] = i;
			operatorIndex++;
		}

	}

	while(operatorIndex > 0)
	{
		popOperator(operatorIndex-1, operandIndex-1, operatorList, operandList, commList);
		operandIndex--;
		operatorIndex--;

	//	printf("stack3:\n");
	//	printStack(operatorIndex-1, operandIndex-1, operatorList, operandList);
	}
	free(operatorList);
	free(operandList);
	rootList[rootListIndex] = operandList[0];
	return returnIndex;
}