Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. def min_distance(from_word, to_word)
  2. count = 0
  3. words = [from_word]
  4. loop {
  5. return count if (words.include?(to_word))
  6. new_words = Array.new
  7. words.each { |word|
  8. index = 0
  9. rindex = -1
  10. index += 1 until (word[index] != to_word[index])
  11. rindex -= 1 until (word[rindex] != to_word[rindex])
  12. if (word.length >= to_word.length)
  13. new_word = word.clone
  14. rnew_word = word.clone
  15. new_word.slice!(index)
  16. rnew_word.slice!(rindex)
  17. end
  18. if (word.length <= to_word.length)
  19. new_word = word.clone
  20. rnew_word = word.clone
  21. new_word.insert(index, to_word[index])
  22. rnew_word.insert(rindex, to_word[rindex])
  23. end
  24. new_words.push(new_word, rnew_word)
  25. if (index < [word.length, to_word.length].min)
  26. new_word = word.clone
  27. new_word[index] = to_word[index]
  28. new_words.push(new_word)
  29. end
  30. if (rindex.abs < [word.length, to_word.length].min)
  31. new_word = word.clone
  32. new_word[rindex] = to_word[rindex]
  33. new_words.push(new_word)
  34. end
  35. }
  36. count += 1
  37. words = new_words
  38. }
  39. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement