All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nutz.el.arithmetic.RPN Maven / Gradle / Ivy

Go to download

Nutz, which is a collections of lightweight frameworks, each of them can be used independently

There is a newer version: 1.r.72
Show newest version
package org.nutz.el.arithmetic;

import java.util.LinkedList;
import java.util.Queue;

import org.nutz.el.ElCache;
import org.nutz.el.Operator;
import org.nutz.el.obj.Elobj;
import org.nutz.lang.util.Context;

/**
 * 逆波兰表示法(Reverse Polish notation,RPN,或逆波兰记法),是一种是由波兰数学家扬·武卡谢维奇1920年引入的数学表达式方式,在逆波兰记法中,所有操作符置于操作数的后面,因此也被称为后缀表示法。
* 参考:逆波兰表达式 * * @author juqkai([email protected]) * */ public class RPN { //存放context private final ElCache ec = new ElCache(); //预编译后的对象 private LinkedList el; public RPN() {} /** * 进行EL的预编译 */ public RPN(Queue rpn) { compile(rpn); } /** * 执行已经预编译的EL */ public Object calculate(Context context){ ec.setContext(context); return calculate(el); } /** * 根据逆波兰表达式进行计算 */ public Object calculate(Context context, Queue rpn) { ec.setContext(context); LinkedList operand = OperatorTree(rpn); return calculate(operand); } /** * 计算 */ private Object calculate(LinkedList el2){ if(el2.peek() instanceof Operator){ Operator obj = (Operator) el2.peek(); return obj.calculate(); } if(el2.peek() instanceof Elobj){ return ((Elobj) el2.peek()).fetchVal(); } return el2.peek(); } /** * 预先编译 */ public void compile(Queue rpn){ el = OperatorTree(rpn); } /** * 转换成操作树 */ private LinkedList OperatorTree(Queue rpn){ LinkedList operand = new LinkedList(); while(!rpn.isEmpty()){ if(rpn.peek() instanceof Operator){ Operator opt = (Operator) rpn.poll(); opt.wrap(operand); operand.addFirst(opt); continue; } if(rpn.peek() instanceof Elobj){ ((Elobj) rpn.peek()).setEc(ec); } operand.addFirst(rpn.poll()); } return operand; } }