peterschussheim
9/20/2016 - 3:39 PM

Map character frequency to character

Map character frequency to character

// 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;
// []
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;

Map character frequency to character

This Gist was automatically created by Carbide, a free online programming environment.

You can view a live, interactive version of this Gist here.