Advertisement
Guest User

Untitled

a guest
Apr 7th, 2015
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.24 KB | None | 0 0
  1. import scala.io.StdIn._
  2. import scala.collection.mutable._
  3.  
  4. object Calculator {
  5.   object Type extends scala.Enumeration {
  6.     type Type = Value
  7.     val NUMBER, OPERATION, OPEN_BR, CLOSE_BR, NONE = Value
  8.   }
  9.  
  10.   import Type._
  11.  
  12.   val tokens = Array(NONE -> " +",
  13.                       NUMBER -> "\\d+.?\\d*",
  14.                       OPEN_BR -> "[(]",
  15.                       CLOSE_BR -> "[)]",
  16.                       OPERATION -> "[+-*\\/]")
  17.  
  18.   def toPolish(input : String) : Array[(Calculator.Type.Value ,Double)] = {
  19.     val result = new ArrayBuffer[(Calculator.Type.Value,Double)]
  20.     var pos = 0
  21.     while(pos < input.length) {
  22.       var isFound = false
  23.       for(tok <- tokens){
  24.         val mat = tok._2.r findFirstMatchIn input.substring(pos)
  25.         if(mat!=None){
  26.           isFound = true
  27.           pos+=mat.get.end
  28.           tok._1 match {
  29.             case NUMBER => result+=(tok._1 -> tok._2.toDouble)
  30.             case OPEN_BR =>
  31.             case CLOSE_BR=>
  32.             case OPERATION=>result+=(tok._1 -> 0)
  33.           }
  34.         }
  35.       }
  36.       if(!isFound)pos=input.length
  37.     }
  38.     result.toArray
  39.   }
  40. }
  41.  
  42. object MyApp extends App {
  43.   val str = readLine
  44.   val array = Calculator.toPolish(str)
  45.   println(array.mkString(","))
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement