在Swift中找到网格中总和的更好方法

问题描述 投票:1回答:1

我有一个带有6x7网格的应用程序,可让用户输入值。获得每个值之后,应用程序将检查是否找到任何连续的值以创建十的总和并执行进一步的代码(对于编写的4个测试用例,我可以很好地工作)。到目前为止,我一直在编写类似于以下内容的if语句:

func findTens() {
        if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue) == 10 {
            //code to execute
        } else if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue + rowOneColumnThreePlaceHolderValue) == 10 {
            //code to execute
        } else if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue + rowOneColumnThreePlaceHolderValue + rowOneColumnFourPlaceHolderValue) == 10 {
            //code to execute
        } else if (rowOneColumnOnePlaceHolderValue + rowOneColumnTwoPlaceHolderValue + rowOneColumnThreePlaceHolderValue + rowOneColumnFourPlaceHolderValue + rowOneColumnFivePlaceHolderValue) == 10 {
            //code to execute
}

距离第一行还没有走到一半,最终将成为一组非常大的if语句(如果我计算正确,则为231,因为单个7列行将是1,2-1,2,3- ...- 2,3-2,3,4 -...- 67,因此每行21种可能性)。我认为必须有一种更简洁的方法,但是我一直在努力寻找更好的方法。

我已经考虑过使用类似于以下内容的每个rowXColumnYPlaceHolderValue变量的数组:

let rowOnePlaceHolderArray = [rowOneColumnOnePlaceHolderValue, rowOneColumnTwoPlaceHolderValue, rowOneColumnThreePlaceHolderValue, rowOneColumnFourPlaceHolderValue, rowOneColumnFivePlaceHolderValue, rowOneColumnSixPlaceHolderValue, rowOneColumnSevenPlaceHolderValue]
        for row in rowOnePlaceHolderArray {
           //compare each element of the array here, 126 comparisons 
        }

但是,除了那些数组元素显然因为复制而不是对原始数组的引用之外,我很难找到这种方法的下一步...

我很幸运地找到了一些我在应用程序中遇到的其他问题的相当聪明的解决方案,但这已经给我带来了大约一个星期的麻烦,所以我想寻求帮助以查看我可能会缺少什么想法。可能没有其他方法比231 if语句方法明显更好,这是可以的。预先谢谢!

swift
1个回答
0
投票

这里有个主意(我的头上;我没有去优化):

func array(_ arr:[Int], rangeOfSum sum: Int) -> Range<Int>? {
    for start in 0..<arr.count-1 {
        let slice = Array(arr[start..<arr.count])
        for n in 2...slice.count {
            let elements = slice.prefix(n)
            if elements.reduce(0, +) == sum {
                return start..<(start+n)
            }
        }
    }
    return nil
}

示例:

let arr = [1, 8, 6, 2, 8, 4]
array(arr, rangeOfSum: 10)
// 3..<5, which is correct; those are the elements 2, 8 which sum to 10

另一个例子:

let arr = [1, 8, 1, 2, 8, 4]
array(arr, rangeOfSum: 10)
// 0..<3, which is correct; those are the elements 1, 8, 1 which sum to 10

边缘情况:

let arr = [1, 8, 3, 2, 9, 4]
array(arr, rangeOfSum: 10)
// nil
© www.soinside.com 2019 - 2024. All rights reserved.