Created
December 24, 2017 03:25
-
-
Save farskid/f5d089d76056040683e92d45f1a447b8 to your computer and use it in GitHub Desktop.
Number of deletions needed to make two random strings, anagrams of each other in Javascript
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
function anagrams(a, b) { | |
var freqA = charFreq(a); | |
var freqB = charFreq(b); | |
var deletions = 0; | |
getChars().forEach(char => { | |
deletions += Math.max(freqA[char], freqB[char]) - Math.min(freqA[char], freqB[char]); | |
}); | |
return deletions; | |
} | |
function getChars() { | |
return 'abcdefghijklmnopqrstuvwxyz'.split(''); | |
} | |
function charFreq(str) { | |
var chars = getChars(); | |
str = str.toLowerCase(); | |
var freq = {}; | |
chars.forEach(char => { | |
var charNum = str.split('').filter(x => x === char); | |
freq[char] = charNum ? charNum.length : 0; | |
}); | |
return freq; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment