ios - 扫描数组查找条件,返回索引以扫描所述索引处的 Array2 值

标签 ios swift

我有两个数组

var Status: [Int] = [0,1,0,1,1] //which will contain at random a 0 or 1 at all five index

var Total: [Int] = [0,85,90,90,0] //which will contain any positive Int at all five index

我想编写一个 func 来扫描 Status 并只返回包含 1 的索引。

然后在这些相同的索引处扫描 Total 以查看 Int 是否相等

在这种情况下,索引 1,3,4 将从 Status 扫描返回,Total 将在 [1,3,4] 处扫描以返回 85, 90,0.

如果我能想出正确的语法,那么就像这样

var Status: [Int] = [0,1,1,1,1]

var Total: [Int] = [3,4,16,2,3]

var IndexesToCompare: [Int] = [Int]()

Status.scan for value '1', return indexes to IndexesToCompare

var TotalsToCompare: [Int] = [Int]()

Total.scan @Index[IndexesToCompare], return values to TotalsToCompare

if TotalsToCompare.scanIfAllIntegarsAreEqual == true {println("EQUAL")} else {println("Unequal")}

这将打印出“不相等”,但如果 Status 更改为 [1,0,0,0,1],它将打印出“EQUAL”

最佳答案

如果我明白你想要什么。您想要查看 Status 并找到所有的 1,并通过这些获得 Total 中的相应值。然后使用这些值找到平均值,然后将其与每个单独的值进行比较。如果所有值都等于平均值​​,则返回 true,否则返回 false。我假设该函数可以访问 Status 和 Total,并且它们的大小相同。如果所有值都相同则返回 true,否则返回 false。

func yourFunc()->Bool{
    var values = [Int]()
    for index in 0..<Status.count{//loop through Status
        if Status[index] == 1{//when you find a 1
            //append it's corresponding value in Total to values
            values.append(Total[index])
        }
    }
    var average = values.reduce(0,+)/values.count
    for value in values{
        if value != average{
            return false
        }
    }
    return true
}

注意:我个人只喜欢大写类而不是变量。

关于ios - 扫描数组查找条件,返回索引以扫描所述索引处的 Array2 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29222039/

相关文章:

ios - 后台设备运动更新

swift - 使用 Swift 从不同的类访问 SKCameraNode

ios - 通过 TabBar 转至 VC

iphone - 如何垂直移动带有 slider 的 UILabel

ios - 在 iOS 13 上的 Swift 中设置 Sign in with Apple for Firebase 时出错的原因是什么?

ios - 另一个 UIScrollView 不滚动

ios - secret 二维码 - 只能由我自己的扫描仪应用读取

Swift 3 - UISplitViewController - 在景观中隐藏/展开主视图(例如 Notes 应用程序)

swift - 如何修复 "does not conform to protocol"

ios - 自动居中以编程方式创建的 UIButtons