Created
February 19, 2015 12:44
-
-
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
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
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