Created
October 3, 2020 11:45
-
-
Save sometimesfood/c16f05099f812986930a087f83bbd231 to your computer and use it in GitHub Desktop.
Simple anagram finder in Ruby
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'set' | |
def usage | |
puts 'usage: #{$PROGRAM_NAME} WORD...' | |
exit(1) | |
end | |
usage if ARGV.length.zero? | |
def permutations(word) | |
characters = word.downcase.split('') | |
characters.permutation(word.length).map(&:join).to_set | |
end | |
def dictionary_words(dictionary_path) | |
File.readlines(dictionary_path) | |
.map(&:downcase) | |
.map(&:chomp) | |
.to_set | |
end | |
def anagrams(word, dictionary) | |
permutations(word) & dictionary | |
end | |
def main | |
dictionary = dictionary_words('/usr/share/dict/words') | |
ARGV.each do |word| | |
puts anagrams(word, dictionary).to_a | |
end | |
end | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment