Search This Blog

Tuesday, October 17, 2017

Find most common word in array of string using swift

Following task - find most common word in array of string.

Algorithm
  1. Create and fill up dictionary of word frequency. Count for each word in array
  2. Find key with maximum value and return this key.

Let's get implemented this algorithm.
let array = ["This", "Test", "Swift", "Never", "Swift", "Test", "Swift"]

func getMostCommonWord(array: [String]) -> String {
    
    var dict = [String: Int]()
    
    for word in array {
        if let count = dict[word] {
            dict[word] = count + 1
        } else {
            dict[word] = 1
        }
    }
    
    var mostCommonWord = ""
    for key in dict.keys {
        if mostCommonWord == "" {
            mostCommonWord = key
        }
        if let nextCount = dict[key], let prevCount = dict[mostCommonWord] {
            if nextCount > prevCount {
                mostCommonWord = key
            }
        }
    }
    
    return mostCommonWord
}

print(getMostCommonWord(array: array))
// Swift

How we can improve this algorithm. Using High-ordered functions. 

We can sort dictionary. As result of sorting dictionary we get descendingly sorted array of tuples. In this array of tuples first element contain key with maximum count. After that we can get first tuple and get key variable from it.
let sortedTuples = dict.sorted { $0.1 > $1.1}
print(sortedTuples)
// [(key: "Swift", value: 3), (key: "Test", value: 2), (key: "This", value: 1), (key: "Never", value: 1)]
print(sortedTuples.first!)
// (key: "Swift", value: 3)

So now we can rewrite our function.
func getMostCommonWordUsingMap(array: [String]) -> String {
    
    var dict = [String: Int]()
    
    for word in array {
        if let count = dict[word] {
            dict[word] = count + 1
        } else {
            dict[word] = 1
        }
    }
    
    var mostCommonWord = ""
    
    if let first = (dict.sorted { $0.1 > $1.1}).first {
        mostCommonWord = first.key
    }
    
    return mostCommonWord
}

print(getMostCommonWordUsingMap(array: array))
// Swift

5 comments:

  1. Your article is one of its kind which explained every bit of Custom Build Website. looking for further valuable articles from you

    ReplyDelete
  2. You've provided some really useful information; I've been looking for material like this, so please keep sharing it as much as you can. Best Custom Websites

    ReplyDelete
  3. Thank you for writing this quality informational content.Your writing technique is impressive and enjoyable to read. I'll come back for more fantastic material.
    Best wishes, and good luck.
    Custom Build Website

    ReplyDelete
  4. your article is unbelievable with accurate information. I see a lot of research after that and that is more than I expectedCustom Build Website

    ReplyDelete
  5. Great share!One of the best blogs I have Ever Seen. Keep going!
    iOS App Testing Services

    ReplyDelete