Created
June 2, 2022 00:12
-
-
Save vgarro/1a32ca895f17ef9dcbe4bf0716894092 to your computer and use it in GitHub Desktop.
Coding Interview challenge.
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
# Create the algorithm to find words based on the following criteria: | |
# search_string = "word" | |
# 1. exact match | |
# 2. one of the words is exact match | |
# 3. starts with | |
# 4. rest, alphanumerically | |
ordered_results = ["Word", "Microsoft Word", "Wordpress", "1Password", "Google AdWords"] | |
results = ordered_results.shuffle | |
class ExactMatch | |
attr_reader :word_list, :search_string | |
def initialize(word_list:, search_string:) | |
@word_list = word_list | |
@search_string = search_string | |
end | |
def sort | |
word_list.select do |word| | |
word.downcase == search_string.downcase | |
end | |
end | |
end | |
class SingleWordMatch | |
attr_reader :word_list, :search_string | |
def initialize(word_list:, search_string:) | |
@word_list = word_list | |
@search_string = search_string | |
end | |
def sort | |
word_list.select do |word| | |
split_words = word.split(" ") | |
split_words.any? do | split_word| | |
split_word.downcase == search_string.downcase | |
end | |
end | |
end | |
end | |
class StartsWithMatch | |
attr_reader :word_list, :search_string | |
def initialize(word_list:, search_string:) | |
@word_list = word_list | |
@search_string = search_string | |
end | |
def sort | |
word_list.select do |word| | |
!!word.downcase.match(/^#{search_string.downcase}/) | |
end | |
end | |
end | |
class DefaultMatch | |
attr_reader :word_list, :search_string | |
def initialize(word_list:, search_string:) | |
@word_list = word_list | |
@search_string = search_string | |
end | |
def sort | |
word_list.sort | |
end | |
end | |
class Sorterer | |
# Order Matters! | |
SORTING_STRATEGIES = [ExactMatch, SingleWordMatch, StartsWithMatch, DefaultMatch] | |
def self.call(word_list:, search_string:) | |
sorting_result = [] | |
SORTING_STRATEGIES.each do |strategy, acc| | |
list_to_sort = word_list - sorting_result | |
instance = strategy.new(word_list: list_to_sort, search_string: search_string) | |
sorting_result += instance.sort.flatten | |
end | |
puts sorting_result.inspect | |
sorting_result.flatten! | |
end | |
def remove_duplicates(word_list:, sorted_list:) | |
end | |
end | |
result = Sorterer.call(word_list: results, search_string: search_string) | |
puts result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment