数组包含一个完整的子阵 [英] Array contains a complete subarray
本文介绍了数组包含一个完整的子阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在斯威夫特我怎么能检查数组是否包含在全部给定的子阵?例如,是否有工作像这样的包含
功能:
让mainArray =你好,世界,这,A,美丽,天]
包含(mainArray,[世界,这是])//将返回true
包含(mainArray,[世界,它])//将返回false
包含(mainArray,[世界,一])//将返回false - 在mainArray不相邻
解决方案
您可以与更高级别的功能做到这一点,是这样的:
FUNC的indexOf(数据:[字符串] _部分:[字符串]) - GT;诠释? {
//这是一系列的prevent建设从零到负
如果part.count> data.count {
零回报
} //本场比赛的指标不能超过data.count,part.count
回报(0 ... data.count-part.count).indexOf {在IND
//从目前的指数构造一个子阵列,
//其内容比较我们所期待的。
[字符串](数据[IND ..< IND + part.count])==部分
}
}
该函数返回的第一个匹配的索引,如果有的话,或无
其他。
您可以按如下方式使用它:
让mainArray =你好,世界,这,A,美丽,天]
如果让指数=的indexOf(mainArray,[世界,这是]){
打印(发现在\\(指数匹配))
}其他{
打印(不匹配)
}
编辑作为扩展到通用阵列...
这现在可用于 Equatable
类型的任意均匀阵列。
扩展Array中元素:Equatable {
FUNC indexOfContiguous(子数组:[元]) - GT;诠释? { //这是一系列的prevent建设从零到负
如果subArray.count> self.count {
零回报
} //本场比赛的指标不能超过data.count,part.count
回报(0 ... self.count-subArray.count).indexOf {在IND
//从目前的指数构造一个子阵列,
//其内容比较我们所期待的。
[元](自[IND ..< IND + subArray.count])==子阵
}
}
}
In Swift how can I check whether an array contains a given subarray in its entirety? E.g., is there a contains
function that works like this:
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
解决方案
You can do it with higher-level functions, like this:
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
}
}
This function returns the index of the first match, if any, or nil
otherwise.
You can use it as follows:
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")
}
Editing in as an extension to a generic array...
This can now be used for any homogeneous array of Equatable
types.
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
}
}
}
这篇关于数组包含一个完整的子阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文