challenge 急勾配の判定

有限の長さの数列で,各要素の値が,その要素の後ろにある残りの列に含まれるすべての要素の和よりも大きい列を「急勾配の列」ということにします(空列の和は0とします).

任意の長さ(ただし有限の長さの)数列を与えられたとき,それが「急勾配の列」であるかどうかを判定する述語関数を定義してください.

必須ではありませんが,効率についてコメントがあれば面白いかもしれませんね.

Posted feedbacks - Scala

 効率優先で。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
object SteepAngle {
    def isSteep(l:List[Int]):Boolean = l match {
            case List() => true
            case _ => {
                def loop(s:Int, r:List[Int]):Boolean = r match {
                        case List() => true
                        case x::xs if x > s => loop(s + x, xs)
                        case _ => false
                    }
                loop(l.last, l.reverse.tail)
            }
        }
    def main(args:Array[String]):Unit =
        try {
            isSteep(args.toList.map(_.toInt)) match {
                case true => println("steep")
                case _ => println("not steep")
            }
        } catch {
            case e => println("usage: SteepAngle NUMBERS")
        }
}

Index

Feed

Other

Link

Pathtraq

loading...