Last active
October 6, 2016 16:14
-
-
Save mauricioklein/ff829d9c4604ddf1ef67d11355e48306 to your computer and use it in GitHub Desktop.
Anagram generator
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
# | |
# 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