Last active
August 29, 2015 14:06
-
-
Save st98/7b34fea6e88f08b8a9a3 to your computer and use it in GitHub Desktop.
freq.js
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 freq(s) { | |
var r = {}, i, k, c; | |
for (i = 0; i < s.length; i++) { | |
c = s.charAt(i); | |
if (!(c in r)) { | |
r[c] = 0; | |
} | |
r[c]++; | |
} | |
return r; | |
} | |
/* desc */ | |
function cmp(a, b) { | |
if (a == b) { | |
return 0; | |
} else if (a < b) { | |
return 1; | |
} | |
return -1; | |
} | |
/** | |
* sort([['a', 2], ['b', 1], ['c', 3]], 1) | |
* => [['c', 3], ['a', 2], ['b', 1]] | |
*/ | |
function sort(a, k) { | |
return a.sort(function (a, b) { | |
return cmp(a[k], b[k]); | |
}); | |
} | |
function p(s) { | |
var f = freq(s), r = [], k; | |
for (k in f) { | |
r.push([k, f[k]]); | |
} | |
return sort(r, 1).map(function (a) { | |
return a.join(' : '); | |
}).join('\n'); | |
} | |
function main() { | |
console.log(p('Hello, world!')); | |
/** | |
* l : 3 | |
* o : 2 | |
* H : 1 | |
* e : 1 | |
* , : 1 | |
* : 1 | |
* w : 1 | |
* r : 1 | |
* d : 1 | |
* ! : 1 | |
*/ | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment