gpt4 book ai didi

arrays - 数组包含一个完整的子数组

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:53 26 4
gpt4 key购买 nike

在 Swift 中,我如何检查一个数组是否完整地包含给定的子数组?例如,是否有一个像这样工作的 contains 函数:

let mainArray = ["hello", "world", "it's", "a", "beautiful", "day"]
contains(mainArray, ["world", "it's"]) // would return true
contains(mainArray, ["world", "it"]) // would return false
contains(mainArray, ["world", "a"]) // would return false - not adjacent in mainArray

最佳答案

你可以用更高级的函数来做,像这样:

func indexOf(data:[String], _ part:[String]) -> Int? {
// This is to prevent construction of a range from zero to negative
if part.count > data.count {
return nil
}

// The index of the match could not exceed data.count-part.count
return (0...data.count-part.count).indexOf {ind in
// Construct a sub-array from current index,
// and compare its content to what we are looking for.
[String](data[ind..<ind+part.count]) == part
}
}

此函数返回第一个匹配项的索引(如果有),否则返回nil

您可以按如下方式使用它:

let mainArray = ["hello", "world", "it's", "a", "beautiful", "day"]
if let index = indexOf(mainArray, ["world", "it's"]) {
print("Found match at \(index)")
} else {
print("No match")
}

作为通用数组的扩展进行编辑...

这现在可以用于 Equatable 类型的任何同类数组。

extension Array where Element : Equatable {
func indexOfContiguous(subArray:[Element]) -> Int? {

// This is to prevent construction of a range from zero to negative
if subArray.count > self.count {
return nil
}

// The index of the match could not exceed data.count-part.count
return (0...self.count-subArray.count).indexOf { ind in
// Construct a sub-array from current index,
// and compare its content to what we are looking for.
[Element](self[ind..<ind+subArray.count]) == subArray
}
}
}

关于arrays - 数组包含一个完整的子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37410649/

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