Last active
August 29, 2015 14:07
-
-
Save mayfer/e262102d6272443f36ff to your computer and use it in GitHub Desktop.
edit distance solutions
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
# An edit distance (e.d.) is defined as how many times you need to replace, add, or remove characters to match two strings. | |
# E.G. "train" and "brain" have e.d.=1 | |
# "train" and "rain" have e.d.=1 | |
# "train" and "trains" have e.d.=1 | |
# Write a method that returns TRUE if edit distance is exactly 1, FALSE if not. | |
def edit_distance_is_one(word1, word2) | |
i1 = 0 | |
i2 = 0 | |
distance = 0 | |
while i1 < word1.length && i2 < word2.length | |
if word1[i1] != word2[i2] | |
distance += 1 | |
if word1.length > word2.length | |
i1 += 1 | |
elsif word2.length > word1.length | |
i2 += 1 | |
else | |
i1 += 1 | |
i2 += 1 | |
end | |
else | |
i1 += 1 | |
i2 += 1 | |
end | |
end | |
distance == 1 | |
end | |
def edit_distance_is_one(word1, word2) | |
long = word1.length >= word2.length ? word1 : word2 | |
short = word2.length <= word1.length ? word2 : word1 | |
i = 0 | |
distance = 0 | |
while i < short.length | |
if long[i] != short[i] | |
distance += 1 | |
if long.length > short.length | |
long.slice!(i) | |
end | |
end | |
i += 1 | |
end | |
distance == 1 | |
end | |
puts edit_distance_is_one("train", "brain") == true | |
puts edit_distance_is_one("train", "rain") == true | |
puts edit_distance_is_one("rain", "brain") == true | |
puts edit_distance_is_one("murat", "brain") == false | |
puts edit_distance_is_one("murat", "murattt") == false | |
puts edit_distance_is_one("murat", "murrrat") == false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment