Skip to content

Instantly share code, notes, and snippets.

@litvil
Created January 23, 2016 21:15
Show Gist options
  • Save litvil/58924841391899786199 to your computer and use it in GitHub Desktop.
Save litvil/58924841391899786199 to your computer and use it in GitHub Desktop.
Creates regullar exp for anagram
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