Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created July 18, 2015 02:26
Show Gist options
  • Save shigemk2/0954f7758df7604ad432 to your computer and use it in GitHub Desktop.
Save shigemk2/0954f7758df7604ad432 to your computer and use it in GitHub Desktop.
// def rpnPrime(str: String): String = str match {
// case str if str(4) == '+' => (str(0).asDigit + str(2).asDigit).toString
// case str if str(4) == '-' => (str(0).asDigit - str(2).asDigit).toString
// case str if str(4) == '*' => (str(0).asDigit * str(2).asDigit).toString
// case str if str(4) == '/' => (str(0).asDigit / str(2).asDigit).toString
// case str if str(4) == '%' => (str(0).asDigit % str(2).asDigit).toString
// case _ => {
// ""
// }
// }
// println(rpnPrime("1 3 +"))
// println(rpnPrime("1 3 h"))
def rpn(str: String): List[String] = {
val xs = str.split(" ").toList
xs.foldLeft(List()){ xs => rpnPrime(xs.take(3)) }
// case xs if xs.length == 3 => rpnPrime(xs)
// case xs => {
// println(xs)
// rpnPrime((rpnPrime(xs.take(3)) + " " + rpn(xs.drop(3).mkString(" "))).split(" ").toList)
// }
}
def rpnPrime(str: List[String]): List[String] = str match {
case x::y::z if z.head == "+" => (y.toInt + x.toInt).toString
case x::y::z if z.head == "-" => (y.toInt - x.toInt).toString
case x::y::z if z.head == "*" => (y.toInt * x.toInt).toString
case x::y::z if z.head == "/" => (y.toInt / x.toInt).toString
case x::y::z if z.head == "%" => (y.toInt % x.toInt).toString
case _ => {
""
}
}
println(rpn("1 3 +"))
println(rpn("1 3 + 5 2 - *"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment