Advertisement
Guest User

Edit Distance Performance Code

a guest
Feb 27th, 2014
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.35 KB | None | 0 0
  1.   def editDistance(word: String, target: String, v0: Array[Int], v1: Array[Int]) = {
  2.  
  3.     def min(a: Int, b: Int, c: Int) = Math.min(a, Math.min(b, c))
  4.    
  5.     val limit = target.size
  6.  
  7.     @tailrec
  8.     def distanceByRow(index: Int, v0: Array[Int], v1: Array[Int]): Int = {
  9.       if (index >= word.length) v0(target.length)
  10.       else {
  11.         v1(0) = index + 1
  12.         // slow code start (note that (0 until target.length) foreach { j => has same performance)
  13.         for (j <- 0 until limit) {
  14.           val cost = if (word(index) == target(j)) 0 else 1
  15.           v1(j + 1) = min(v1(j) + 1, v0(j + 1) + 1, v0(j) + cost);
  16.         }
  17.         // slow code end
  18.         // fast code start
  19.         @tailrec
  20.         def distanceByColumn(col: Int): Unit = {
  21.           if (col < limit) {
  22.             val cost = if (word(index) == target(col)) 0 else 1
  23.             v1(col + 1) = min(v1(col) + 1, v0(col + 1) + 1, v0(col) + cost);
  24.             distanceByColumn(col + 1)
  25.           }
  26.         }
  27.         distanceByColumn(0)
  28.         // fast code end
  29.         distanceByRow(index + 1, v1, v0)
  30.       }
  31.     }
  32.  
  33.     // initialize v0 as previous row of distances (starts as edit distance for empty 'word')
  34.     for { i <- v0.indices } v0(i) = i
  35.  
  36.     // recursively process rows matching characters in word being compared to find best
  37.     distanceByRow(0, v0, v1)
  38.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement