Skip to content

Commit

Permalink
Minimum Edit Distance updated to Swift 4
Browse files Browse the repository at this point in the history
  • Loading branch information
shabirjan committed Aug 1, 2017
1 parent 0e0ae64 commit 99d955a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions Minimum Edit Distance/MinimumEditDistance.playground/Contents.swift 100755 → 100644
@@ -1,21 +1,26 @@
extension String {
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif

extension String {

public func minimumEditDistance(other: String) -> Int {
let m = self.characters.count
let n = other.characters.count
var matrix = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: m + 1)

// initialize matrix
for index in 1...m {
// the distance of any first string to an empty second string
matrix[index][0] = index
}

for index in 1...n {
// the distance of any second string to an empty first string
matrix[0][index] = index
}

// compute Levenshtein distance
for (i, selfChar) in self.characters.enumerated() {
for (j, otherChar) in other.characters.enumerated() {
Expand All @@ -25,7 +30,7 @@ extension String {
} else {
// minimum of the cost of insertion, deletion, or substitution
// added to the already computed costs in the corresponding cells
matrix[i + 1][j + 1] = min(matrix[i][j] + 1, matrix[i + 1][j] + 1, matrix[i][j + 1] + 1)
matrix[i + 1][j + 1] = Swift.min(matrix[i][j] + 1, matrix[i + 1][j] + 1, matrix[i][j + 1] + 1)
}
}
}
Expand Down
Empty file.

0 comments on commit 99d955a

Please sign in to comment.