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.

closest.go 963B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package flags
  2. func levenshtein(s string, t string) int {
  3. if len(s) == 0 {
  4. return len(t)
  5. }
  6. if len(t) == 0 {
  7. return len(s)
  8. }
  9. dists := make([][]int, len(s)+1)
  10. for i := range dists {
  11. dists[i] = make([]int, len(t)+1)
  12. dists[i][0] = i
  13. }
  14. for j := range t {
  15. dists[0][j] = j
  16. }
  17. for i, sc := range s {
  18. for j, tc := range t {
  19. if sc == tc {
  20. dists[i+1][j+1] = dists[i][j]
  21. } else {
  22. dists[i+1][j+1] = dists[i][j] + 1
  23. if dists[i+1][j] < dists[i+1][j+1] {
  24. dists[i+1][j+1] = dists[i+1][j] + 1
  25. }
  26. if dists[i][j+1] < dists[i+1][j+1] {
  27. dists[i+1][j+1] = dists[i][j+1] + 1
  28. }
  29. }
  30. }
  31. }
  32. return dists[len(s)][len(t)]
  33. }
  34. func closestChoice(cmd string, choices []string) (string, int) {
  35. if len(choices) == 0 {
  36. return "", 0
  37. }
  38. mincmd := -1
  39. mindist := -1
  40. for i, c := range choices {
  41. l := levenshtein(cmd, c)
  42. if mincmd < 0 || l < mindist {
  43. mindist = l
  44. mincmd = i
  45. }
  46. }
  47. return choices[mincmd], mindist
  48. }