具有查找“沙漏”和计算总和的算法
object Hourglass2D {
def main(args: Array[String]) {
val sc = new java.util.Scanner(System.in)
var n = sc.nextInt()
var arr = new Array[Int](n)
for (arr_i <- 0 until n) {
arr(arr_i) = sc.nextInt()
}
var res = -2147483648
for (i <- 0 until arr.length - 2) {
for (j <- 0 until arr.length - 2) {
val sum = checkSum(arr, i, j, j + 2) + checkSum(arr, i + 1, j + 1, j + 1) + checkSum(arr, i + 2, j, j + 2)
if (sum > res) res = sum
}
}
println(res)
}
private def checkSum(arr: Array[Array[Int]], row: Int, first: Int, last: Int) = {
var sum = -1
for (i <- first until last + 1) {
sum = sum + arr(row)(i)
}
sum + 1
}
正如你所看到的,我使用了可变状态,比如var。任何想法如何使用val而不是var?
感谢。
答案 0 :(得分:2)
构建arr
存在一些问题,所以我会跳过它。您可以使用for {...} yield
表达式构建总和,然后使用max
添加常量并找到最大值:
object Hourglass2D {
def main(args: Array[String]) {
val arr: Array[Array[Int]] = ???
val sums: Seq[Int] = for {
i <- 0 until arr.length - 2
j <- 0 until arr.length - 2
} yield checkSum(arr, i, j, j + 2) +
checkSum(arr, i + 1, j + 1, j + 1) +
checkSum(arr, i + 2, j, j + 2)
val res = (sums :+ -2147483648).max
println(res)
}
// as suggested in comment:
private def checkSum(arr: Array[Array[Int]], row: Int, first: Int, last: Int) = {
arr(row).slice(first, last+1).sum
}
}
答案 1 :(得分:0)
您可以使用两个foldLeft
编写第一个函数:
val res = -2147483648
(0 until (arr.length-2)).foldLeft(res) { case (acc, i) =>
(0 until (arr.length-2)).foldLeft(acc) { case (acc2, j) =>
val sum = checkSum(arr, i, j, j + 2) + checkSum(arr, i + 1, j + 1, j + 1) + checkSum(arr, i + 2, j, j + 2)
if(sum > acc2) sum else acc2
}
}
您可以使用foldLeft
编写秒函数:
(first until (last+1)).foldLeft(0) { case (acc, i) => acc + arr(row)(i)}
正如@TzachZohar所提到的,有一些打字问题!