Last active
September 1, 2016 21:57
-
-
Save evmorov/250aa796431448471b844f9570ceda9b to your computer and use it in GitHub Desktop.
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
class Nickname | |
def initialize | |
@dict = File.readlines('enable1.txt').map(&:strip) | |
end | |
def generate(name) | |
name = name.downcase.gsub(/\W+/, '') | |
substrings(name).reduce([]) do |names, substring| | |
return names.map(&:capitalize).join(', ') if names.any? && substring.size < names.last.size | |
(@dict.include? substring) ? names.push(substring) : names | |
end | |
end | |
def substrings(str) | |
Array.new(Array.new(str.size, 1).join.to_i(2)) do |n| | |
binary = "%0#{str.size}b" % (n + 1) | |
binary.chars.each_with_index.map { |e, i| e == '1' ? str.chars[i] : nil }.compact.join | |
end.uniq.select { |sub| sub[0] == str[0] }.sort_by(&:size).reverse | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment