Created
July 4, 2019 03:06
-
-
Save jubishop/d4cf3a20f93d504191f450f5db785558 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def min_distance(from_word, to_word) | |
return 0 if from_word == to_word | |
count = 0 | |
words = [from_word] | |
loop { | |
new_words = Array.new | |
words.uniq.each { |word| | |
index = 0 | |
rindex = -1 | |
index += 1 until (word[index] != to_word[index]) | |
rindex -= 1 until (word[rindex] != to_word[rindex]) | |
if (word.length >= to_word.length) | |
new_word = word.clone | |
rnew_word = word.clone | |
new_word.slice!(index) | |
rnew_word.slice!(rindex) | |
return count+1 if (new_word == to_word or rnew_word == to_word) | |
end | |
if (word.length <= to_word.length) | |
new_word = word.clone | |
rnew_word = word.clone | |
new_word.insert(index, to_word[index]) | |
rnew_word.insert(rindex, to_word[rindex]) | |
return count+1 if (new_word == to_word or rnew_word == to_word) | |
end | |
new_words.push(new_word, rnew_word) | |
max_length = [word.length, to_word.length].min | |
if (index < max_length) | |
new_word = word.clone | |
new_word[index] = to_word[index] | |
new_words.push(new_word) | |
return count+1 if new_word == to_word | |
end | |
if (rindex.abs < max_length) | |
new_word = word.clone | |
new_word[rindex] = to_word[rindex] | |
new_words.push(new_word) | |
return count+1 if new_word == to_word | |
end | |
} | |
count += 1 | |
words = new_words | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment