gpt4 book ai didi

algorithm - 具有不可变状态的二维数组处理

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:31 26 4
gpt4 key购买 nike

有寻找“沙漏”和计算总和的算法

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 ?

谢谢。

最佳答案

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
}
}

关于algorithm - 具有不可变状态的二维数组处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37348174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com