Skip to content

Instantly share code, notes, and snippets.

@sometimesfood
Created October 3, 2020 11:45
Show Gist options
  • Save sometimesfood/c16f05099f812986930a087f83bbd231 to your computer and use it in GitHub Desktop.
Save sometimesfood/c16f05099f812986930a087f83bbd231 to your computer and use it in GitHub Desktop.
Simple anagram finder in Ruby
#!/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