昨天在微信上看到一道题,“编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34–5 + 67–8 + 9 = 100”,最近在学习scala,想想就用scala实现吧,实现代码如下:
var totalList = List(List(""))
def sum(n: Int,pre: String,list: List[String]):Unit =
for(i <- List("+", "-", "")){
val tuple = i match{
case "" => (pre + n,list)
case _ => (i + n,list :+ pre)
}
n match {
case 9 => totalList = totalList :+ (tuple._2 :+ tuple._1)
case _ => sum(n + 1,tuple._1,tuple._2)
}
}
var s = sum(1,"0",Nil)
for(i <- totalList.filter(i => i.length >3) if (0 /: i)(_.toInt+_.toInt) == 100)
println(i.mkString("").substring(1)+"=" + (0 /: i)(_.toInt+_.toInt))
最后scala解释器执行下输出结果如下: