Created
September 8, 2023 16:05
-
-
Save j4rs/8fa7f11a11a049f3aadee82ec82f4acd to your computer and use it in GitHub Desktop.
Max word letter span problem
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
# Given some text, write a function to find the max word letter span and list of words with that span | |
# Word letter span is defined as the alphabetical distance in between the first and last letters of the word | |
# Rules | |
# The same two letters produce the same span regardless of their order in the word | |
#. “PAT” and “TAP” have span 4 | |
# Capitalization does not matter | |
#. “Pat” and “pat” have span 4 | |
# Words that begin and end with the same letter have a word span of 0 | |
#. “pop” and “I” have span 0 | |
# Examples | |
# "pat" -> 'p' to 't' = 4 | |
# "Float" -> 'f' to 't' = 14 | |
# "wood" -> 'w' to 'd' = abs(-19) = 19 | |
# "would" -> 'w' to 'd' = 19 | |
# "I" -> 'I' to 'I' = 0 | |
# "pop" -> 'p' to 'p' = 0 | |
# Output from this function should be the span and the list of words with that span | |
# Given: “I would trade two wood for a sheep but not three wood." | |
# Expect: 19, ["would", "wood"] or 19, ["wood", "would"] | |
def word_span(word) | |
abc_indexes = ("a".."z").to_a | |
chars = word.downcase.chars | |
first_letter = chars.first | |
last_letter = chars.last | |
distance = abc_indexes.find_index(first_letter) - abc_indexes.find_index(last_letter) | |
distance.positive? ? distance : distance * -1 | |
end | |
def sentence_span(sentence) | |
words = sentence.split(/\W/).uniq | |
word_spans = words.map { |word| [word_span(word), word] } | |
max_span = word_spans.map(&:first).max | |
word_spans | |
.select { |ws| ws[0] == max_span } | |
.reduce({}) do |hash, ws| | |
key, val = ws | |
hash[key.to_s] ||= [] | |
hash[key.to_s] << val | |
hash | |
end | |
end | |
# Test the function | |
puts word_span("pat") == 4 | |
puts word_span("Float") == 14 | |
puts word_span("wood") == 19 | |
puts word_span("doow") == 19 | |
puts word_span("I") == 0 | |
puts word_span("pop") == 0 | |
puts(sentence_span('I would trade two wood for a sheep but not three wood.') == {"19"=>["would", "wood"]}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment