Skip to content

Instantly share code, notes, and snippets.

@Papierkorb
Created May 1, 2017 14:10
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 Papierkorb/4b1977b3bfffccc46fb13b107e66e983 to your computer and use it in GitHub Desktop.
Save Papierkorb/4b1977b3bfffccc46fb13b107e66e983 to your computer and use it in GitHub Desktop.
def find_anagram(word, list)
small_word = word.downcase
word_chars = small_word.chars.sort
list.map(&.downcase) # Only care about downcase'd for now
.map_with_index{|x, i| {x, i}} # But keep the index
.reject{|(x, _)| x == small_word} # Throw out equals
.select{|(x, _)| x.chars.sort == word_chars} # Find anagrams
.uniq(&.first) # Throw out duplicates
.map{|(_, i)| list[i]} # Restore case of input word
.to_a # Done.
end
pp find_anagram "Hello", %w[ olleH Car olleH Hlleo ]
pp find_anagram "Hello", %w[ Car ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment