Created
January 23, 2016 21:15
-
-
Save litvil/58924841391899786199 to your computer and use it in GitHub Desktop.
Creates regullar exp for anagram
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
def anagram(input) | |
lookaheadPart = '' | |
matchingPart = '^' | |
positiveLookaheadPrefix='(?=' | |
positiveLookaheadSuffix=')' | |
letters = input.to_s.split('') | |
inputCharacterFrequencyMap = letters.reduce(Hash.new(0)) { |a, b| a[b] += 1; a } | |
inputCharacterFrequencyMap.each do |letter, freq| | |
lookaheadPart += positiveLookaheadPrefix; | |
freq.times{ | |
lookaheadPart += '.*' | |
lookaheadPart += letter | |
matchingPart += '.' | |
} | |
lookaheadPart += positiveLookaheadSuffix | |
end | |
matchingPart += '$' | |
lookaheadPart + matchingPart | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment