You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.2 KiB

  1. // Copyright (c) 2014 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package search
  15. import (
  16. "math"
  17. )
  18. func LevenshteinDistance(a, b string) int {
  19. la := len(a)
  20. lb := len(b)
  21. d := make([]int, la+1)
  22. var lastdiag, olddiag, temp int
  23. for i := 1; i <= la; i++ {
  24. d[i] = i
  25. }
  26. for i := 1; i <= lb; i++ {
  27. d[0] = i
  28. lastdiag = i - 1
  29. for j := 1; j <= la; j++ {
  30. olddiag = d[j]
  31. min := d[j] + 1
  32. if (d[j-1] + 1) < min {
  33. min = d[j-1] + 1
  34. }
  35. if a[j-1] == b[i-1] {
  36. temp = 0
  37. } else {
  38. temp = 1
  39. }
  40. if (lastdiag + temp) < min {
  41. min = lastdiag + temp
  42. }
  43. d[j] = min
  44. lastdiag = olddiag
  45. }
  46. }
  47. return d[la]
  48. }
  49. // LevenshteinDistanceMax same as LevenshteinDistance but
  50. // attempts to bail early once we know the distance
  51. // will be greater than max
  52. // in which case the first return val will be the max
  53. // and the second will be true, indicating max was exceeded
  54. func LevenshteinDistanceMax(a, b string, max int) (int, bool) {
  55. la := len(a)
  56. lb := len(b)
  57. ld := int(math.Abs(float64(la - lb)))
  58. if ld > max {
  59. return max, true
  60. }
  61. d := make([]int, la+1)
  62. var lastdiag, olddiag, temp int
  63. for i := 1; i <= la; i++ {
  64. d[i] = i
  65. }
  66. for i := 1; i <= lb; i++ {
  67. d[0] = i
  68. lastdiag = i - 1
  69. rowmin := max + 1
  70. for j := 1; j <= la; j++ {
  71. olddiag = d[j]
  72. min := d[j] + 1
  73. if (d[j-1] + 1) < min {
  74. min = d[j-1] + 1
  75. }
  76. if a[j-1] == b[i-1] {
  77. temp = 0
  78. } else {
  79. temp = 1
  80. }
  81. if (lastdiag + temp) < min {
  82. min = lastdiag + temp
  83. }
  84. if min < rowmin {
  85. rowmin = min
  86. }
  87. d[j] = min
  88. lastdiag = olddiag
  89. }
  90. // after each row if rowmin isn't less than max stop
  91. if rowmin > max {
  92. return max, true
  93. }
  94. }
  95. return d[la], false
  96. }