Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement