package org.lvcp.eepperly.simplify;

import org.lvcp.eepperly.expr.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by eepperly16 on 12/14/15.
 */
public class DefaultSimplifier extends AbstractSimplifier {
	public Expr simplify(Expr expression){
		List<Expr> args = expression.getArguments();
		for (int i=0;i<args.size();i++){
			args.set(i, simplify(args.get(i)));
		}
		if (expression instanceof Product){ //combines numerical terms, flattens products
			List<NumConstant> numTerms = new ArrayList<>();
			Expr temp;
			for (int i=0;i<args.size();i++){
				temp = args.get(i);
				if (temp instanceof NumConstant) {
					numTerms.add((NumConstant) temp);
					args.remove(i);
				}
				else if (temp instanceof Product){
					args.addAll(temp.getArguments());
					args.remove(i);
				}
			}
			NumConstant constantTerm = NumConstant.product(numTerms);
			if (Expr.ZERO.equals(constantTerm)) return Expr.ZERO;
			else if (!Expr.ONE.equals(constantTerm)) args.add(constantTerm);
			if (args.size()==1) return args.get(0);
			return (new Product(args));
		}
		else if (expression instanceof Sum){ //combines numerical terms, flattens sums
			List<NumConstant> numTerms = new ArrayList<>();
			Expr temp;
			for (int i=0;i<args.size();i++){
				temp = args.get(i);
				if (temp instanceof NumConstant) {
					numTerms.add((NumConstant) temp);
					args.remove(i);
				}
				else if (temp instanceof Sum){
					args.addAll(temp.getArguments());
					args.remove(i);
				}
			}
			NumConstant constantTerm = NumConstant.sum(numTerms);
			if (!Expr.ZERO.equals(constantTerm)) args.add(constantTerm);
			if (args.size()==1) return args.get(0);
			return (new Sum(args));
		}
		else{
			return expression;
		}
	}
}


@@ -288,16 +288,107 @@
 ession)%7B
+ //function takes an expression argument and outputs a simplified version of the expression
 %0A%09%09List%3C
@@ -457,24 +457,67 @@
 size();i++)%7B
+ //simplify all of the individual arguments
 %0A%09%09%09args.set
@@ -674,32 +674,58 @@
 w ArrayList%3C%3E();
+ //list of numerical terms
 %0A%09%09%09Expr temp;%0A%09
@@ -811,33 +811,32 @@
 eof NumConstant)
- 
 %7B%0A%09%09%09%09%09numTerms.
@@ -851,32 +851,80 @@
 Constant) temp);
+ //add numerical term to list of numerical terms
 %0A%09%09%09%09%09args.remov
@@ -1004,32 +1004,51 @@
 getArguments());
+ //flattens product
 %0A%09%09%09%09%09args.remov
@@ -1116,32 +1116,65 @@
 oduct(numTerms);
+ //multiplies all numerical terms
 %0A%09%09%09if (Expr.ZER
@@ -1348,32 +1348,61 @@
  Product(args));
+ //returns simplified product
 %0A%09%09%7D%0A%09%09else if (
@@ -2009,16 +2009,52 @@
 %0A%09%09else%7B
+ //if not sum or product return self
 %0A%09%09%09retu

Comment default simplifier