Skip to content

Instantly share code, notes, and snippets.

@syhily
Last active November 9, 2016 06:48
Show Gist options
  • Select an option

  • Save syhily/b573fd33cd8e433bcb574771a3fd3279 to your computer and use it in GitHub Desktop.

Select an option

Save syhily/b573fd33cd8e433bcb574771a3fd3279 to your computer and use it in GitHub Desktop.
降雨趣题 Scala 实现 http://www.ituring.com.cn/article/273313
object Count extends App {
def sliceFromMaxElement(array: Array[Int]) = {
val (left, right) = array.span(_ < array.max)
(left, right.tail.reverse)
}
def fold(array: Array[Int], result: Int = 0): Int = {
if (array.isEmpty) {
result
} else {
val (left, right) = sliceFromMaxElement(array)
fold(left, right.fold(result)((sum, i) => sum + array.max - i))
}
}
def calculate(seq: Array[Int] = Array(0)): Int = {
val (left, right) = sliceFromMaxElement(seq)
fold(left) + fold(right)
}
override def main(args: Array[String]): Unit = {
if(args.isEmpty){
println(calculate(Array(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)))
} else {
println(calculate(args.map(_.toInt)))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment