Last active
March 13, 2021 18:37
-
-
Save algal/9403f238179a71824d39319b19257817 to your computer and use it in GitHub Desktop.
Look for a subarray in an array in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Collection { | |
/// True if `self` is a range within `collection` | |
/// - Parameter collection: a `Collection` like `Array` | |
/// - Returns: true or false | |
/// | |
/// Since this works with `Collection` it works with `Array`, `ArraySlic`, etc.. | |
func isSubcollection<U>(of collection:U) -> Bool | |
where U:Collection, U.Element == Self.Element, Self.Element:Equatable | |
{ | |
let (a,b) = (collection,self) | |
for i in a.indices { | |
var matches:Bool = true | |
var i_runahead = i | |
for j in b.indices { | |
if b[j] != a[i_runahead] { | |
matches = false | |
break; | |
} | |
i_runahead = a.index(after: i_runahead) | |
} | |
if matches { return true } | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment