View Javadoc
1   package visitor;
2   
3   import calculator.Expression;
4   import calculator.operations.Operation;
5   import calculator.atoms.Complex;
6   import calculator.atoms.IntegerAtom;
7   import calculator.atoms.Rationnal;
8   import calculator.atoms.Real;
9   import calculator.functions.*;
10  
11  /**
12   * Counter is a visitor that counts the numbers, operations,
13   * and depth in an arithmetic expression.
14   */
15  public class Counter extends Visitor {
16  
17  	private int nbOps = 0;
18  	private int nbNbs = 0;
19  	private int maxDepth = 0;
20  	private int currentDepth = 0;
21  
22  	/**
23  	 * Default constructor.
24  	 */
25  	public Counter() {
26  	}
27  
28  	@Override
29  	public void visit(Real r) {
30  		nbNbs += 1;
31  		maxDepth = Math.max(maxDepth, currentDepth);
32  	}
33  
34  	@Override
35  	public void visit(IntegerAtom i) {
36  		nbNbs += 1;
37  		maxDepth = Math.max(maxDepth, currentDepth);
38  	}
39  
40  	@Override
41  	public void visit(Complex c) {
42  		nbNbs += 1;
43  		maxDepth = Math.max(maxDepth, currentDepth);
44  	}
45  
46  	@Override
47  	public void visit(Rationnal q) {
48  		nbNbs += 1;
49  		maxDepth = Math.max(maxDepth, currentDepth);
50  	}
51  
52  	/**
53  	 * Visit an operation: increments the operation count, then recursively
54  	 * visits all child expressions to accumulate counts.
55  	 *
56  	 * @param o The operation being visited
57  	 */
58  	@Override
59  	public void visit(Operation o) {
60  		nbOps++;
61  		currentDepth++;
62  		for (Expression a : o.getArgs()) {
63  			a.accept(this);
64  		}
65  		currentDepth--;
66  	}
67  
68  	@Override
69  	public void visit(UnaryFunction o) {
70  		nbOps++;
71  		currentDepth++;
72  		o.getArg().accept(this);
73  		currentDepth--;
74  	}
75  
76  	@Override
77  	public void visit(BinaryFunction f) {
78  		nbOps++;
79  		currentDepth++;
80  		f.getFirstArg().accept(this);
81  		f.getSecondArg().accept(this);
82  		currentDepth--;
83  	}
84  
85  	/**
86  	 * Gets the number of operations.
87  	 * 
88  	 * @return The number of operations in the expression
89  	 */
90  	public int getNbOps() {
91  		return nbOps;
92  	}
93  
94  	/**
95  	 * Gets the number of numbers.
96  	 * 
97  	 * @return The number of numbers in the expression
98  	 */
99  	public int getNbNbs() {
100 		return nbNbs;
101 	}
102 
103 	/**
104 	 * Gets the depth.
105 	 * 
106 	 * @return The depth (0 for a number, 1 for a simple operation, etc.)
107 	 */
108 	public int getDepth() {
109 		return maxDepth;
110 	}
111 
112 }