Created
June 8, 2014 18:19
-
-
Save JanX2/a62521c31e04eb741c0e to your computer and use it in GitHub Desktop.
Comparison of two approaches: one not using, one using optionals.
This file contains hidden or 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
/** | |
* Determine the common prefix elements of two collections. | |
* @param collection1 First collection. | |
* @param collection2 Second collection. | |
* @return The number of elements common to the start of each collection. | |
*/ | |
func commonPrefixLength<T: Swift.Collection, U: Swift.Collection where | |
T: Sequence, U: Sequence, | |
T.GeneratorType.Element: Equatable, | |
T.GeneratorType.Element == U.GeneratorType.Element> | |
(collection1: T, collection2: U) -> T.IndexType.DistanceType { | |
var collection2generator = collection2.generate() | |
var i: T.IndexType.DistanceType = 0 | |
for element1 in collection1 { | |
let element2 = collection2generator.next() | |
if (element1 != element2) { | |
return i | |
} | |
i++ | |
} | |
return i | |
} | |
commonPrefixLength("abX", "abc") |
This file contains hidden or 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
/** | |
* Determine the common prefix elements of two collections. | |
* @param collection1 First collection. | |
* @param collection2 Second collection. | |
* @return The number of elements common to the start of each collection. | |
*/ | |
func commonPrefixLength<T: Swift.Collection, U: Swift.Collection where | |
T: Sequence, U: Sequence, | |
T.GeneratorType.Element: Equatable, | |
T.GeneratorType.Element == U.GeneratorType.Element> | |
(collection1: T, collection2: U) -> T.IndexType.DistanceType { | |
var collection2generator = collection2.generate() | |
var i: T.IndexType.DistanceType = 0 | |
for element1 in collection1 { | |
let optionalElement2 = collection2generator.next() | |
if let element2 = optionalElement2 { | |
if (element1 != element2) { | |
return i | |
} | |
} | |
else { | |
break | |
} | |
} | |
return i | |
} | |
commonPrefixLength("abX", "abc") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment