This Gist was automatically created by Carbide, a free online programming environment.
Last active
October 6, 2016 21:22
-
-
Save peterschussheim/f6e2a8507994ab47188affd19ba04ba5 to your computer and use it in GitHub Desktop.
Map character frequency to character
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
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; |
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
// 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