Skip to content

Instantly share code, notes, and snippets.

@hzhu
Created April 29, 2016 20:55
Show Gist options
  • Save hzhu/2c8a6d64236e4c7a42933bbbe6f87ea2 to your computer and use it in GitHub Desktop.
Save hzhu/2c8a6d64236e4c7a42933bbbe6f87ea2 to your computer and use it in GitHub Desktop.
////////////////////////
// Solution #1 -- Adnan
////////////////////////
function pairs (obj) {
var arr = [], key
for (key in obj) arr.push([key, obj[key]])
return arr
}
var string = document.body.innerText
var counts = {}, order
string.split('').forEach(function (d) { counts[d] = (counts[d] || 0) + 1 })
order = pairs(counts).sort(function (a, b) { return a[1] - b[1] }).reverse()
order.forEach(function (d) { console.log(d[0] + ':' + d[1]) })
///////////////////////
// Solution #2 -- Chris
///////////////////////
var str = "some loooooong string";
var obj = [];
for (var i=0; i<str.length; i++) {
var letter = str[i];
if (typeof obj[letter] == "undefined") {
obj[letter] = 0;
}
obj[letter]++;
}
//array of strs
var r = [];
for (key in obj) {
r.push(obj[key] +" : "+key);
}
r.sort().reverse();
for (var i=0; i< r.length; i++) {
var tStr = r[i].split(":");
console.log(tStr[1]+" : "+ tStr[0]);
}
///////////////////////
// Solution #3 -- Henry
///////////////////////
var string = "some loooooong string";
var myObj = {};
var charOccur = function (string) {
//counted characters
for (var i = 0; i < string.length; i++) {
if (string[i] = myObj[string[i]]) {
myObj[string[i]] = myObj[string[i]] + 1;
} else {
myObj[string[i]] = 1;
}
}
//push each key value pair into array
var myArray = [];
for (key in myObj) {
myArray.push(myObj[key] + ":" + key);
}
//sort myArray
var sortedArray = myArray.sort(function(a,b){
return parseInt(b) - parseInt(a);
});
// reverse the key and value
_.each(sortedArray, function(index){
var reverseFix = index.split(":").reverse().join(":");
console.log(reverseFix);
});
};
charOccur(string);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment