Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save peterschussheim/f6e2a8507994ab47188affd19ba04ba5 to your computer and use it in GitHub Desktop.
Save peterschussheim/f6e2a8507994ab47188affd19ba04ba5 to your computer and use it in GitHub Desktop.
Map character frequency to character
function updateCounts(str) {
var arrChars = [];
var totalCount;
// Loop through string and accumulate character counts
var len = str.length;
for(var i = 0; i < len; i++)
{
if(!arrChars[str[i]]) {
arrChars[str[i]] = 1;
} else {
arrChars[str[i]] += 1;
}
}
var countChars = arrChars.count;
var sortedChars = [];
for(var i in arrChars)
{
sortedChars.push(zeroPad(i.charCodeAt(0), 5, '0'));
}
sortedChars.sort();
// Print the character counts
var len = sortedChars.length;
var strToPrint;
for(i = 0; i < sortedChars.length; i++) {
var character = String.fromCharCode(sortedChars[i]);
if(sortedChars[i] == 10) {
character = 'LF'
}
if(sortedChars[i] == 9) {
character = 'TAB'
}
strToPrint = 'Code: ' + zeroPad(sortedChars[i].replace(/^0+/,""), 5, " ");
strToPrint += ' 0x' + parseInt(sortedChars[i].replace(/^0+/,"")).toString(16).toUpperCase();
strToPrint += ' \'' + character + '\'';
strToPrint += ' Count: ' + arrChars[String.fromCharCode(sortedChars[i])] + "\n";
var txt = strToPrint;
}
// Print total character count
txt;
console.log('-----TOTAL CHARACTERS: ' + str.length + "\n");
}
// n = number you want padded
// digits = length you want the final output
function zeroPad(n, digits, padChar) {
n = n.toString();
while (n.length < digits) {
n = padChar + n;
}
return n;
}
var mississippi = updateCounts("mississippi");
mississippi;
// freqOfChars :: String -> {String, Number} ///- Given a string is input, **return an array of each character in str and the number of occurrences in str.**
function freqOfChars(str) {
var obj = {};
for (var i = 0; i < str.length; i += 1) {
var char = str[i];
if (!(char in obj)) {
Object.defineProperty(obj, char, {
writable: true,
value: '1'
});
} else if (char in obj) {
obj.char += 1;
}
}
return obj;
}
var mississippi = freqOfChars("mississippi");
mississippi;
// []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment