gpt4 book ai didi

arrays - Swift 3 中数组平衡点的公共(public)函数

转载 作者:行者123 更新时间:2023-11-28 15:06:05 25 4
gpt4 key购买 nike

我能够使用 Swift 3 Playgrounds 找到数组的平衡点。现在,我正在尝试创建一个方法 (func),它将循环遍历数组并应用我的代码。这是我在 Swift 3 Playgrounds 中的代码:

import Foundation

let myArray = [1, 2, 5, 8, 4, 4]
let divSum = myArray.reduce(0, {$0 + $1}) / 2
print (divSum)
var myBalancePoint = Int()

if myArray[0] + myArray[1] >= divSum {
myBalancePoint = myArray[1]
} else {
if myArray[0] + myArray[1] + myArray[2] >= divSum {
myBalancePoint = myArray[2]
} else {
if myArray[0] + myArray[1] + myArray[2] + myArray[3] >= divSum {
myBalancePoint = myArray[3]
} else {
if myArray[0] + myArray[1] + myArray[2] + myArray[3] + myArray[4] >= divSum {
myBalancePoint = myArray[4]
} else {
if myArray[0] + myArray[1] + myArray[2] + myArray[3] + myArray[4] + myArray[5] >= divSum {
myBalancePoint = myArray[5]
}
}
}
}
}
print (myBalancePoint)

最佳答案

这是一个可能的实现:

func balancePoint(of a: [Int]) -> Int? {
var leftSum = 0
var rightSum = a.reduce(0, +)
for (idx, elem) in a.enumerated() {
rightSum -= elem
if leftSum == rightSum {
return idx
}
leftSum += elem
}
return nil
}

例子:

let myArray = [1, 2, 5, 8, 4, 4]
if let bp = balancePoint(of: myArray) {
print("Balance point index:", bp, "Value:", myArray[bp])
} else {
print("No balance point")
}

输出:

Balance point index: 3 Value: 8

How does it work?

    var leftSum = 0
var rightSum = a.reduce(0, +)

分别是当前元素左边和右边所有元素的当前总和。

    for (idx, elem) in a.enumerated() {

遍历数组,将idx设置为当前索引和 elem 到当前数组元素。

        rightSum -= elem
if leftSum == rightSum {
return idx
}
leftSum += elem

先从右边的和中减去当前元素。如果左右之和相等,那么我们就找到了平衡点。否则为下一次迭代更新左和并继续。

    }
return nil

没有找到平衡点:返回nil

关于arrays - Swift 3 中数组平衡点的公共(public)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48472151/

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