Binary Tree Postfix Calculator - java

I'm making a Postfix calculator where I must use stack objects and a Binary tree during the translation of an expression from infix to a parse tree during the evaluation of a postfix expression.
Can someone please translate?
I have developed a postfix calculator method and I've developed a method that changes an expression from infix to postfix, but I don't understand what I am being asked to do. I can enter an expression in infix and calculate it fine as well as convert it to postfix, but I cannot determine what exactly I am being asked to create here.
An example of how to essentially do this in pseudocode would be very helpful or just an explanation of how to store a mathematical expression into a binary tree as well as how to evaluate an expression in a binary tree with stack into a parse tree.
I'll also say I'm a little unsure what a parse tree is.
Any explanation would be very much appreciated.
It is an assignment for a class, so it can be seen here if this was inadequate information: http://www.cs.gsu.edu/jbhola/csc3410/Spring13/assign6_expre_tree.html
My main point here is I just don't quite understand what I'm supposed to do or how I'm supposed to do it. We weren't taught how to program any of this and we lack a textbook so I'm just kind of blindly trying to wrap my head around the whole project :/

Imagine you have a node like AddNode which has two values
class AddNode {
final double a, b;
double value() {
return // how could you return the value of this node?
}
}
Making it more generic
interface Node { double value(); }
class AddNode implements Node {
final Node a, b;
double value() {
return // something which gives the value of this node.
}
}

Related

How to Implement Binary Search Trees (Within the parameters of my questions)?

I am struggling in a data structures course where my professor is either absent or not answering. I have an assignment due within a day or so and have no clue where to even start in terms of answering them. If somebody could explain what to do and how it'd be much appreciated. Also, I'm somewhat new to StackOverflow, if I misformatted my question or did something wrong please let me know before a downvote, I would just like some help, thanks.
Write the definition of the method nodeCount that returns the number of nodes in a binary tree. Add this method to the class BinaryTree and create a program (the main class with the main method) to test this method. (Note: To test your algorithm, first create a binary search tree).
Write a method, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Add this method to the class BinaryTree and create a program (the main class with the main method) to test this method. (Note: To test your algorithm, first create a binary search tree).
You can find a tutorial on how to implement a binary tree in java here.
To count the nodes in a tree you should try to use a recursive method that count's and summs up the size of the sub-trees. In pseudocode:
int count(TreeNode node):
if (node.hasNoMoreSubNodes):
return 1
else:
sum = count(node.left) + count(node.right) + 1
return sum
I'm not quite shure what's the point in the second question. You could do something like this (pseudocode):
void swapSubTrees(TreeNode node):
TreeNode tmp = node.left
node.left = node.right
node.right = tmp
This would swap the subtrees of the binary-tree, but after this the structure you have is no longer a binary-search-tree, but only a binary-tree. So this operation would be quite useless if it's executed on a binary-search-tree...
Hope this helps.

How to parse a mathematical function just once and use its result several times

I'm going to write a program that calculate the zeros of a given function. I decided to write a parser to parse that function (I have never written one before). It's a real-valued function of a real variable like "sin(1/x)+exp(x)". I want to use root finding methods like Bisection and Newton. Since these methods are iterative I want to avoid evaluating the function each time in a loop for each point x. So before I make an effort to write my own parser I want to know that is it possible to parse just once and evaluate the function f at points x0, x2, ..., xn without re-parsing f for each x?
There are two standard approaches to this problem:
Parse the formula into what is called an "abstract syntax tree" (AST). This is a compiler data structure that represents the structure of the formula, and it can be inspected quickly by code. It is also possible to evaluate the AST as a formula relatively quickly. See my SO answer
on building recursive descent parsers that support the above tasks:
Is there an alternative for flex/bison that is usable on 8-bit embedded systems?
Somehow compile the formula into your programming language. This often involves first building the AST, and then translating the AST into your programming lanuage terms, running your compiler on that result, and then loading the compiled result. This may be awkward with a compiled language such as C because the absence of dynamic linking; it is easier with languages such as Java or C# because they sort of encourage dynamic loading.
As you can guess, this approach is more effort, but the payoff is that the formula can now be evaluated as quickly as your programming language can do it. You can do this by ad hoc (e.g., recursive descent) parsing and translation, or you do tackle this in a more regular manner using a tool that "rewrites" one syntax into another: https://softwarerecs.stackexchange.com/a/31379/101
As Ira has already pointed out, you parse your expression to an abstract syntax tree. An abstract syntax tree fitting your would look similar to this:
interface AstNode {
double eval(double x);
}
class ConstantNode implements AstNode {
double value;
double eval(double x) {
return value;
}
}
class VariableNode implements AstNode {
double eval(double x) {
return x;
}
}
class OperatorNode implements AstNode {
char op;
AstNode left;
AstNode right;
double eval(double x) {
switch (op) {
case '+': return left.eval(x) + right.eval(x);
case '-': return left.eval(x) - right.eval(x);
case '/': return left.eval(x) / right.eval(x);
case '*': return left.eval(x) * right.eval(x);
case '^': return Math.pow(left.eval(x), right.eval(x));
default:
throw new RuntimeException("Invalid op " + op);
}
}
}
class Function implements AstNode {
...
After you have parsed your expression to the tree, you can just call eval() with the values you are interested in.
Maybe you can do that with Java Scripting Support. For example, it should be possible to evaluate the function in Javascript (Nashorn).
Pro: you don't need to parse the function yourself. Just serve the scripting API.

Replacing Mathematical Operators with Variable Java

Currently trying to do a reverse polish calculator for one of my Uni homework tasks.
I have the program working fine when using a bunch of if/else statements to work out which operator was typed in and do the mathematical operation normally like num1+num2.
This is beyond the homework task we were set but what I'm trying to do now is replace the operator with a variable for example: "num1 + num2" would become "num1 variable num2" where variable equals "+" etc.
Is there a way to do this in Java?
Thanks in advance
Since you are interested in going beyond the scope of the training material, and assuming you've learned about interfaces already, I believe what you are looking for is a binary expression tree (that wikipedia article actually explains it good).
Basically, you create an interface Expression with a double compute() method. There will be two types of implementing classes:
Operand: Constant and Variable.
Operator: Plus, Minus, Multiply, Divide. Each will have two Expression fields: left and right.
Your text expression is then parsed into the expression tree:
// input: "num1 + num2 * 3"
// result expression tree will be built by parser using:
Expression a = new Variable("num1");
Expression b = new Variable("num2");
Expression c = new Constant(3);
Expression d = new Multiply(b, c);
Expression e = new Plus(a, d);
Map<String, Double> variables = /*defined elsewhere*/;
double result = e.compute(variables);
Your new assignment, should you choose to accept it, will be to write the expression classes and a parser to build the expression tree from a text expression.
Hope this will encourage you to go way beyond the training material, having some fun while playing.
First you can use a switch on String rather than if-then-else chain. Another way is to build a static final Map (E.g. HashMap) from String to Function. The strings are the operators. The Functions do the operation. In Java 8 you can give the functions as lambdas. I only have access through a phone right now so can't show code. Your question will be much better received if you add code showing what you mean.

How to get binary subexpressions with javaparser

I am using javaparser to parse the AST for Java source files.
I would like to get all binary subexpressions in the source code as individual nodes.
Here is the source code I am parsing:
class MyClass {
public MyClass() {
double x = (4 / 10.0) + 15;
}
}
I implemented a Visitor that accepts the built-in BinaryExp type, but the only node that it finds contains the binary expression:
(4 / 10.0) + 15
Is there a way to visit the subexpression "(4 / 10.0)" as well?
I tried getting the full expression's "left operand", but it is of type Expression, and not BinaryExpr as I expected.
Any help would be appreciated.
The left operand cannot be of actual type Expression because Expression is an abstract class.
You can check the actual type by checking binEx.getLeft() instanceof BinaryExp.If this evaluates true, you can cast to BinaryExpression.
But probably it evaluates false and the node is of type EnclosedExpr (parentheses). Then the binary expression is the child of the left node
This will probably not solve the whole problem. I think you missed to apply the visitor to the child nodes. You have to adjust visit(BinaryExpr n, A arg):
if you use a GenericVisitorAdaptor you will have to call super.visit(n,arg)
if you wrote your own adaptor you will have to call accept(this, arg) on each child.

Trying to understand parsers

I'm trying to use JavaCC to build a simple command line calculator that can handle a variety of expressions. While there are plenty of tutorials out there on how to write grammars, none that I've seen so far explain what happens afterwards.
What I understand right now is that after a string is passed into the parser, it's split into a tokens and turned into a parse tree. What happens next? Do I traverse through the parse tree doing a bunch of if-else string comparisons on the contents of each node and then perform the appropriate function?
I highly suggest you watch Scott Stanchfield's ANTLR 3.x tutorials. Even if you don't end up using ANTLR, which may be overkill for your project but I doubt it, you will learn a lot by watching him go through the thought process.
In general the process is...
Build a lexer to understand your tokens
Build a parser that can validate and understand and organize the input into an abstract syntax tree (AST) which should represent a simplified/easy-to-work-with version of your syntax
Run any calculation based on the AST
You need to actually compile or interpret it according to what you need..
For a calculator you just need to visit the tree recursively and evaluate the parsed tree while with a more complex language you would have to translate it to an intermediate language which is assembly-like but keeps abstraction from the underlying architecture.
Of course you could develop your own simple VM that is able to execute a set of instruction in which your language compiles but it would be overkill in your case.. just visit the parse tree. Something like:
enum Operation {
PLUS, MINUS
}
interface TreeNode {
float eval();
}
class TreeFloat implements TreeNode {
float val;
float eval() { return val; }
}
class TreeBinaryOp implements TreeNode {
TreeNode first;
TreeNode second;
Operation op;
float eval() {
if (op == PLUS)
return first.eval()+second.eval();
}
Then you just call the eval function on the root of the tree. A semantic checking could be needed (with the construction of a symbol table too if you plan to have variables or whatever).
Do I traverse through the parse tree doing a bunch of if-else string comparisons on the contents of each node and then perform the appropriate function?
No, there's no need to build a parse tree to implement a calculator. In the parts of the code where you would create a new node object, just do the calculations and return a number.
JavaCC allows you to choose any return type for a production, so just have your's return numbers.
Some parser generators (such as YACC) let you put actions within the grammar so when you apply a certain production you can also apply a defined action during that production.
E.g. in YACC:
E: NUM + NUM {$$ = $1.value + $2.value};
would add the values of NUM and return the result to the E non-terminal.
Not sure what JavaCC lets you do.

Categories