scala 实现布尔表达式的计算

来源:互联网 发布:人工智能对人类的意义 编辑:程序博客网 时间:2024/04/29 14:50
import scala.collection.mutable.ArrayStackobject App{  def main(args:Array[String]){    val b = Array(true,true,true,true)    val v = Array("(","0","or","(","1","and","2",")",")","and","!","3","#")    val st1 = new ArrayStack[String]()    val st2 = new ArrayStack[Boolean]()    st1.push("#")    val pos = Map("and"->1,"or"->1,"!"->3,"#"-> -1)    val pis = Map("and"->1,"or"->1,"!"->0,"#"-> -1,"("-> -1)    for(i<- 0 until v.size){      if(v(i)=="and"||v(i)=="or"||v(i)=="!"){        if(pos(v(i))>pis(st1.top))          st1.push(v(i))        else{          while(pos(v(i))<=pis(st1.top)){            val c = st1.pop() match{              case "and" => st2.pop&&st2.pop              case "or" => st2.pop||st2.pop               case "!" => !st2.pop            }            st2.push(c)          }          st1.push(v(i))        }      }      else if(v(i)=="("){        st1.push("(")      }      else if(v(i)==")" || v(i)=="#"){        while(st1.top!="(" && st1.top!="#"){            val c = st1.pop() match{              case "and" => st2.pop&&st2.pop              case "or" => st2.pop||st2.pop              case "!" => !st2.pop            }            st2.push(c)        }        st1.pop()      }      else{        st2.push(b(v(i).toInt))      }    }    println(st2.top)  }}

0 0
原创粉丝点击