Skip to content

Instantly share code, notes, and snippets.

@donburks
Forked from mayfer/edit_distance.rb
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donburks/a96b010046fb6877fdf4 to your computer and use it in GitHub Desktop.
Save donburks/a96b010046fb6877fdf4 to your computer and use it in GitHub Desktop.
# 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.
# Author: Murat Ayfer
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