Created
March 6, 2017 00:13
-
-
Save mtso/2ee35d422da5cbd5c475ed1548aca928 to your computer and use it in GitHub Desktop.
451. Sort Characters By Frequency: Given a string, sort it in decreasing order based on the frequency of characters.
This file contains 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
/** | |
* @param {string} s | |
* @return {string} | |
*/ | |
var frequencySort = function(s) { | |
var map = {}; | |
s.split('').forEach(function(char) { | |
map[char] = map[char] ? map[char] + 1 : 1; | |
}); | |
map = getEntries(map).sort(function(a, b) { | |
return b[1] - a[1]; | |
}); | |
return map.reduce(function(ret, freq) { | |
return ret + pad(freq); | |
}, ''); | |
}; | |
/** | |
* @param {object} object | |
* @return {array} 2D-array of object key/value pairs | |
*/ | |
function getEntries(object) { | |
var entries = []; | |
Object.keys(object).forEach(function(key) { | |
entries.push([key, object[key]]); | |
}); | |
return entries; | |
} | |
/** | |
* @param {array} freq | |
* @return {string} | |
*/ | |
function pad(freq) { | |
var padded = ''; | |
for (var i = 0; i < freq[1]; i++) { | |
padded += freq[0]; | |
} | |
return padded; | |
} | |
/** | |
* @param {any} actual | |
* @param {any} expected | |
* @param {string} testName | |
* @return {undefined} | |
*/ | |
function assertEqual(actual, expected, testName) { | |
if (actual === expected) { | |
console.log('passed'); | |
} else { | |
console.log('FAILED [' + testName + '] Expected "' + expected + '" but got "' + actual + '"'); | |
} | |
} | |
/** | |
* @param {array} actual | |
* @param {array} expected | |
* @param {string} testName | |
* @return {boolean} | |
*/ | |
function assertDimensionalArraysEqual(actual, expected, testName) { | |
if (Object.prototype.toString.call(actual) !== '[object Array]') { | |
return actual === expected; | |
} | |
var isEqualLength = actual.length === expected.length; | |
var isEqualItems = expected.every(function(item, index) { | |
return assertDimensionalArraysEqual(item, actual[index], testName); | |
}); | |
if (isEqualItems && isEqualLength) { | |
console.log('passed'); | |
return true; | |
} else { | |
console.log('FAILED [' + testName + '] Expected "' + expected + '" but got "' + actual + '"'); | |
return false; | |
} | |
} | |
var testVal = "cababa"; | |
assertEqual(pad(['a', 3]), 'aaa', 'pads the character into a string'); | |
assertDimensionalArraysEqual( | |
getEntries({'a': 3, 'b': 2}), | |
[['a', 3], ['b', 2]], | |
'maps an object into a 2D array' | |
); | |
assertEqual(frequencySort(testVal), 'aaabbc', 'sorts a string'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment