Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created July 4, 2019 02:06
Show Gist options
  • Save jubishop/6092c69d4bbce3c251e23ea003d8329a to your computer and use it in GitHub Desktop.
Save jubishop/6092c69d4bbce3c251e23ea003d8329a to your computer and use it in GitHub Desktop.
def min_distance(from_word, to_word)
count = 0
words = [from_word]
loop {
return count if (words.include?(to_word))
new_words = Array.new
words.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)
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])
end
new_words.push(new_word, rnew_word)
if (index < [word.length, to_word.length].min)
new_word = word.clone
new_word[index] = to_word[index]
new_words.push(new_word)
end
if (rindex.abs < [word.length, to_word.length].min)
new_word = word.clone
new_word[rindex] = to_word[rindex]
new_words.push(new_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