Skip to content

Instantly share code, notes, and snippets.

@nicholasaiello
Last active October 15, 2017 02:14
Show Gist options
  • Save nicholasaiello/681f059be4b54daa4e79c847931cf1a5 to your computer and use it in GitHub Desktop.
Save nicholasaiello/681f059be4b54daa4e79c847931cf1a5 to your computer and use it in GitHub Desktop.
/**
determine character frequency of provided input: ex, "chicago"
print the frequency as follows
c: **
h: *
i: *
a: *
g: *
o: *
*
******
chiago
*/
const input = "chicago";
const values = {}; // use as a Set
// build data set
let maxFrequency = 0;
const keys = input.split('').filter((ch) => {
const contains = ch in values;
if (!contains) {
values[ch] = 1;
} else {
values[ch] += 1;
}
if (values[ch] > maxFrequency) {
maxFrequency = values[ch];
}
return !contains;
});
function printRow(key, value) {
return `${key}: ` + Array.from({length: value}).map((x, i) => '*').join('') + "\n";
}
// vertical output
let result1 = keys.reduce((row, k, i) => (
row + printRow(k, values[k])
), '');
// horizontal output: stars
let result2 = '';
for (let i = maxFrequency; i > 0; i--) {
result2 += keys.reduce((line, k, n) => (
line + ((values[k] >= i) ? '*' : " ")
), '') + "\n"
}
// horizontal output: chars
result2 += keys.reduce((row, k, i) => row + k)
console.log(result1);
console.log(result2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment