Skip to content

Instantly share code, notes, and snippets.

@timhuff
Created February 19, 2015 12:44
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 timhuff/5b5a72e47549b522e126 to your computer and use it in GitHub Desktop.
Save timhuff/5b5a72e47549b522e126 to your computer and use it in GitHub Desktop.
Algorithm for testing if two strings of the form /[A-Z][a-z]*/ are anagrams
isAnagram = (a,b)->
if a.length != b.length
return false
[a,b] = [a,b].map (x)->x.toLowerCase().split('')
length = a.length
if length > 12852
throw new Error "This algorithm can only reliably handle strings smaller than 12,852 characters"
anagramHash = (hash, letter)->
charCode = letter.charCodeAt(0)-96
if !(1 <= charCode <= 26)
throw new Error "This algorithm is for the purpose of comparing strings of the form /[A-Za-z]*/"
hash+(length*charCode)
a.reduce(anagramHash, 0) == b.reduce(anagramHash, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment