Created
November 6, 2014 19:49
-
-
Save imouaddine/8284d641984307280363 to your computer and use it in GitHub Desktop.
Minimum distance between two words in a string
This file contains 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 distance(a,b) | |
words = "I am a good girl".split(/\W+/) | |
a_found = false | |
b_found = false | |
prev = nil | |
words.each_with_index do |word, index| | |
if word == a | |
prev ||= index | |
a_found = true | |
end | |
if word == b | |
prev ||= index | |
b_found = true | |
end | |
if a_found && b_found | |
return index - prev | |
end | |
end | |
-1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment