Skip to content

Instantly share code, notes, and snippets.

@mauricioklein
Last active October 6, 2016 16:14
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 mauricioklein/ff829d9c4604ddf1ef67d11355e48306 to your computer and use it in GitHub Desktop.
Save mauricioklein/ff829d9c4604ddf1ef67d11355e48306 to your computer and use it in GitHub Desktop.
Anagram generator
#
# ANAGRAM GENERATOR
#
# Author: Mauricio Klein (mauricio [dot] klein [dot] msk [at] gmail [dot] com)
# Date: October 6th, 2016
#
#
# USAGE:
# $ ruby anagram.rb <a word>
#
def normalize(str)
str.strip.tr(
'ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž',
'AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz'
)
end
if ARGV.empty?
STDERR.puts "Usage: #{$0} <word>"
exit 1
end
# Most Linux/MAC distributions have a words
# file on the path below.
# If this is not your case, just download a dict file
# and adjust the path below.
#
# PtBR dictionary suggestions:
# https://raw.githubusercontent.com/mateus/utils/master/distancia-levenshtein/wordlist-pt-br.txt
DICTIONARY = '/home/klein/Desktop/ptbr.txt'
# Normalize the input word, removing
# all accents and control characters
word = normalize(ARGV.first).downcase
word_length = word.length
# Generate all word permutations
permutations = word
.split(//)
.permutation(word_length)
.map(&:join)
# Try to match each word in dictionary with
# the permutations list.
#
# If a match occurs, an anagram was found
anagrams = []
File.open(DICTIONARY) do |file|
file.each_line do |line|
line_normalized = normalize(line)
anagrams << line_normalized if permutations.include?(line_normalized)
end
end
puts anagrams
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment