Scala 936
type O=Option[(Char,Int)]
type Q=(O,O)
type L=List[Q]
val N=None
def t(a:Int,b:Int):Q=if(a>b)(Some('-',a-b),(if(b!=0&&b*(a/b)==a)Some('/',a/b)else N))else
(Some('+',b-a),(if(a!=0&&a*(b/a)==b)Some('*',b/a)else N))
def w(a:Q,b:Q)=if(a._1==b._1&&a._2==b._2)a else
if(a._1==b._1)(a._1,N)else
if(a._2==b._2)(N,a._2)else(N,N)
def n(l:L):Q=l match{case Nil=>(N,N)
case x::Nil=>x
case x::y::Nil=>w(x,y)
case x::y::xs=>n(w(x,y)::xs)}
def z(l:L,w:Int)=for(d<-1 to w)yield
n(l.drop(d-1).sliding(1,w).flatten.toList)
def h(s:L):Boolean=s.isEmpty||(s(0)!=(N,N))&& h(s.tail)
def j(s:L,i:Int=1):Int=if(h(z(s,i).toList))i else j(s,i+1)
def k(b:Int,o:Char,p:Int)=o match{case'+'=>b+p
case'-'=>b-p
case'*'=>b*p
case _=>b/p}
val e=getLine
val i=e.split(" ").map(_.toInt).toList
val s=i.sliding(2,1).toList.map(l=>t(l(0),l(1)))
val H=n(s.drop(s.size%j(s)).sliding(1,j(s)).flatten.toList)
val c=H._1.getOrElse(H._2.get)
println (k(i(i.size-1),c._1,c._2))
vô dụng:
type O = Option[(Char, Int)]
def stepalize (a: Int, b: Int): (O, O) = (a > b) match {
case true => (Some('-', a-b), (if (b!=0 && b * (a/b) == a) Some ('/', a/b) else None))
case false=> (Some('+', b-a), (if (a!=0 && a * (b/a) == b) Some ('*', b/a) else None)) }
def same (a: (O, O), b: (O, O)) = {
if (a._1 == b._1 && a._2 == b._2) a else
if (a._1 == b._1) (a._1, None) else
if (a._2 == b._2) (None, a._2) else
(None, None)}
def intersection (lc: List[(O, O)]): (O, O) = lc match {
case Nil => (None, None)
case x :: Nil => x
case x :: y :: Nil => same (x, y)
case x :: y :: xs => intersection (same (x, y) :: xs)}
def seriallen (lc: List[(O, O)], w: Int= 1) =
for (d <- 1 to w) yield
intersection (lc.drop (d-1).sliding (1, w).flatten.toList)
def hit (s: List[(O, O)]) : Boolean = s match {
case Nil => true
case x :: xs => (x != (None, None)) && hit (xs)}
def idxHit (s: List[(O, O)], idx: Int = 1) : Int =
if (hit (seriallen (s, idx).toList)) idx else
idxHit (s, idx+1)
def calc (base: Int, op: Char, param: Int) = op match {
case '+' => base + param
case '-' => base - param
case '*' => base * param
case _ => base / param}
def getOp (e: String) = {
val i = e.split (" ").map (_.toInt).toList
val s = i.sliding (2, 1).toList.map (l => stepalize (l(0), l(1)))
val w = idxHit (s)
val hit = intersection (s.drop (s.size % w).sliding (1, w).flatten.toList)
val ci = hit._1.getOrElse (hit._2.get)
val base = i(i.size - 1)
println ("i: " + i + " w: " + w + " ci:" + ci + " " + calc (base, ci._1, ci._2))
}
val a="1 3 5 7 9 11"
val b="1 3 2 4 3 5 4 6 5 7 6"
val c="2 6 7 3 9 10 6 18 19 15 45 46"
val d="1024 512 256 128 64 32 16"
val e="1 3 9 8 24 72 71 213 639"
val f="1 2 3 4 5 2 3 4 5 6 3 4 5 6 7"
val g="1 2 4 1 3 9 5 8 32 27 28 56 53 55 165 161 164 656 651 652 1304"
val h="0 0 1 2 3 6 7 14"
val i="0 0 0 0 1 0 0 0 0 1 0"
List (a, b, c, d, e, f, g, h, i).map (getOp)
Thất bại thảm hại với Peter Taylor h, nhưng tôi không thấy khả năng chữa lành chương trình trong một khoảng thời gian hợp lý.