Could you please explain me one thing in Swift Playground?

editDistance() -> https://github.com/raywenderlich/swift-algorithm-club/tree/master/Minimum%20Edit%20Distance

It’s license -> https://github.com/raywenderlich/swift-algorithm-club/blob/master/LICENSE.txt

// Looks through the potentialMatches array to find the item that most closely matches the string in the first argument, and returns that string.

func closestMatch(for string: String, from potentialMatches: [String]) -> String {

    // Initialize the best edit distance to the worst possible value

    var bestEditDistance = Int.max

    // Initialize the index of the best match to the first index

    var bestMatchIndex = 0

    

    for i in 0 ..< potentialMatches.count {

        // Get the potential match at index i

        

        // Get the edit distance from the string to the potential match

        

        // If the distance calculated above is better than best edit distance,

        // update the best edit distance and best match index

        let potentialMatch = potentialMatches[i]

        let distance = editDistance(from: string, to: potentialMatch)

        

        if distance < bestEditDistance {

            bestMatchIndex = i

            bestEditDistance = distance

        }

    }

    

    return potentialMatches[bestMatchIndex]

}

Could you please explain why we initialize bestEditDistance like Int.max ? I don't understand what does this instance mean.

Answered by Claude31 in 710650022

If I understand, bestEditDistance will be some real value found.

Initializing with an exceptionally large number (Int.max), means that if you do not find a position that "matches", then it will stay with this very large value, which is of course unreal value to which any real value will be smaller.

At the end of search loop, if you test bestEditDistance and it is equal to Int.max, you know for sure it was not found. That is the case if potentialMatches.count == 0, as the code inside the for loop is never executed.

Accepted Answer

If I understand, bestEditDistance will be some real value found.

Initializing with an exceptionally large number (Int.max), means that if you do not find a position that "matches", then it will stay with this very large value, which is of course unreal value to which any real value will be smaller.

At the end of search loop, if you test bestEditDistance and it is equal to Int.max, you know for sure it was not found. That is the case if potentialMatches.count == 0, as the code inside the for loop is never executed.

Could you please explain me one thing in Swift Playground?
 
 
Q