Last active
March 10, 2019 01:07
-
-
Save mathonsunday/ef56941c644e3161c473a50af81508d6 to your computer and use it in GitHub Desktop.
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
| import Foundation | |
| import PlaygroundSupport | |
| func wordsWith(prefix: String, in dictionary: [String]) -> [String] { | |
| var output: [String] = [] | |
| let prefixCount = prefix.count | |
| let prefixCharArray = Array(prefix) | |
| wordLoop: for word in dictionary { | |
| let charArray = Array(word) | |
| var wordIndex = 0 | |
| var prefixIndex = 0 | |
| while prefixIndex < prefixCount { | |
| if charArray[wordIndex] != prefixCharArray[prefixIndex] { | |
| continue wordLoop | |
| } | |
| wordIndex += 1 | |
| prefixIndex += 1 | |
| } | |
| output.append(word) | |
| } | |
| return output | |
| } | |
| let dictionary = ["CAT", "DOG", "BUNNY", "CAN", "CUT", "DOLL"] | |
| print(wordsWith(prefix: "CA", in: dictionary)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If we need to implement
hasPrefixourselves, then I feel like thezipfunction would work well here as a good way to iterate through the two strings character by character without having to manually deal with tracking and updating indices.It eliminates having to worry about the index out of bounds errors that @eneko brought up and still works in situations where the prefix is longer than the word since the
zipfunction will stop when one of the sequences it is supplied as input has no more remaining elements.There is also an added benefit that it allows for a more generic extension on
Sequence. If we are manually subscripting and tracking the indices as anInt, then the most generic we could get would be an extension onCollectionwith awhereclause specifying that the collection'sIndexis anInt.The only problem I see with this custom implementation of
hasPrefixis if the function must be case insensitive. Since the only requirement of this extension is that theElementconforms toEquatablewe'd have to further constrain Element to get access to thelowercased()method.