Last active
August 29, 2015 14:22
-
-
Save shunjikonishi/0391bdbc7ba5ebe28b02 to your computer and use it in GitHub Desktop.
問5回答 40分くらい
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.softantenna.com/wp/software/5-programming-problems/ | |
// Problem 5 | |
case class Expr(str: String, ret: Int) { | |
def plus(n: Int) = Expr(str + " + " + n, ret + n) | |
def minus(n: Int) = Expr(str + " - " + n, ret - n) | |
def concat(n: Int) = { | |
val next = last match { | |
case 0 => ret * 10 + n | |
case x if (x < 0) => ret - x + (x * 10) - n | |
case x if (x > 0) => ret - x + (x * 10) + n | |
} | |
Expr(str + n.toString, next) | |
} | |
def last: Int = str.split(" ").toList.takeRight(2) match { | |
case n :: Nil => 0 | |
case "+" :: n :: Nil => n.toInt | |
case "-" :: n :: Nil => 0 - n.toInt | |
case _ => throw new IllegalStateException() | |
} | |
def calc(n: Int) = plus(n) :: minus(n) :: concat(n) :: Nil | |
override def toString = str + " = " + ret | |
} | |
object Test { | |
def main(args: Array[String]): Unit = { | |
val list = (2 to 9).toList | |
val seed = List(Expr("1", 1)) | |
list.foldLeft(seed) { case (ret, n) => | |
ret.flatMap(_.calc(n)) | |
}.filter(_.ret == 100).foreach(println) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment