Last active
May 8, 2018 00:00
-
-
Save rbaumbach/58dc89ad29fee6aa3a4e041095f2d345 to your computer and use it in GitHub Desktop.
ubt2.txt
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
// Tests that I used to get my solution | |
import Quick | |
import Nimble | |
@testable import AlgorithmsAndDataStructuresInSwift | |
// Problem: Write a method that returns the total amount of words for a given input word | |
// ex: Input String: "Billy goat is a fiery, but kind goat that is also a black goat" | |
// word to search for: "goat" -> 3 | |
class String_NumberOfWordsFoundSpec: QuickSpec { | |
override func spec() { | |
describe("#numberOfWordsFound(word:)") { | |
it("returns 0 when the string is empty") { | |
expect("".numberOfWordsFound(word: "dude")).to(equal((0))) | |
} | |
it("returns 0 when word is not found in the original input string") { | |
expect("Today is the day".numberOfWordsFound(word: "goat")).to(equal(0)) | |
} | |
it("returns the total number of occurances of given input word from input string") { | |
let inputString = "Billy goat is a fiery, but kind goat that is also a black goat" | |
expect(inputString.numberOfWordsFound(word: "goat")).to(equal(3)) | |
} | |
it("is case insensitive") { | |
let inputString = "I Am USing GooFy CaSIng" | |
expect(inputString.numberOfWordsFound(word: "goofy")).to(equal(1)) | |
} | |
} | |
} | |
} | |
// My implementation | |
import Foundation | |
extension String { | |
// Mark: - Public Methods | |
func numberOfWordsFound(word: String) -> Int { | |
guard self != "" else { | |
return 0 | |
} | |
let wordDict = addWordsToDict() | |
if let numberOfWords = wordDict[word.lowercased()] { | |
return numberOfWords | |
} else { | |
return 0 | |
} | |
} | |
// MARK: - Private Methods | |
private func addWordsToDict() -> [String: Int] { | |
let splitSentence = self.components(separatedBy: " ") | |
var wordDict: [String: Int] = [:] | |
splitSentence.forEach { word in | |
let lowercaseWord = word.lowercased() | |
if let countOfWord = wordDict[lowercaseWord] { | |
wordDict[lowercaseWord] = countOfWord + 1 | |
} else { | |
wordDict[lowercaseWord] = 1 | |
} | |
} | |
return wordDict | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment