Created
December 8, 2023 01:03
-
-
Save theevo/e719a1cbcfadd6042da21a9679533dd1 to your computer and use it in GitHub Desktop.
Interview practice using Swift
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 | |
| // Write a function in swift that takes a sentence as input and returns the count of each word in the sentence. Ignore punctuation and consider words as case-insensitive. For example, given the input "Hello, world! hello", the function should return ["hello": 2, "world": 1] | |
| func wordCount(str: String) -> [String: Int] { | |
| // if empty input string, return empty dict | |
| guard !str.isEmpty else { | |
| return [:] | |
| } | |
| // what is the minimum word count? can we accept "a" or "I"? yes | |
| // what is character limit of input string? | |
| // what would be a legit word? "asdf asdf asdf liuhj ❌🔥" [a-zA-Z] | |
| // 1. remove the punctuation | |
| // 2. lowercase all letters | |
| var string = str | |
| .components(separatedBy: .punctuationCharacters) | |
| .joined(separator: "") | |
| .components(separatedBy: .symbols) | |
| .joined(separator: "") | |
| .lowercased() | |
| // 3. split the words by whitespace -> array | |
| var words = string.components(separatedBy: .whitespaces) | |
| var dict: [String: Int] = [:] | |
| // 4. go through array of words | |
| for word in words { | |
| guard !word.isEmpty else { | |
| continue | |
| } | |
| // - if the word exists in the dict, then we increment the value (+1) | |
| if let wordCount = dict[word] { | |
| dict[word] = wordCount + 1 | |
| // - if we see a new word, then we insert that word into dict with value 1 | |
| } else { | |
| dict[word] = 1 | |
| } | |
| } | |
| return dict | |
| } | |
| var greeting = "Hello, playground" | |
| let test1 = wordCount(str: "Hello, world! hello") | |
| print(test1) // ["hello": 2, "world": 1] | |
| let test2 = wordCount(str: "") | |
| print(test2) // [:] | |
| let test3 = wordCount(str: "!@#*&$% !@#&$%^ ())*%-=") | |
| print(test3) // [:] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment