Last active
November 9, 2016 06:48
-
-
Save syhily/b573fd33cd8e433bcb574771a3fd3279 to your computer and use it in GitHub Desktop.
降雨趣题 Scala 实现 http://www.ituring.com.cn/article/273313
This file contains hidden or 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
| 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