Created
July 2, 2020 23:17
-
-
Save 3on/d6306fa37ca649da5b41557183187701 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // store and display a histogram | |
| // input = [1, 2, 3, 4, 5, 10, 11, 11] | |
| // bin_size = 5 | |
| // first bin [1, 2, 3, 4] -> 4 | |
| // second bin [5] -> 1 | |
| // ... | |
| // 0 | #### | |
| // 5 | # | |
| // 10| ### | |
| const group = (numbers, binSize) => { | |
| const max = numbers[numbers.length - 1]; | |
| const nb = Math.ceil(max / binSize); | |
| let res = []; | |
| for(let i = 0; i < nb; ++i) { | |
| res.push([]); | |
| } | |
| let j = 0; | |
| for(let i = 0; i < numbers.length; ++i) { | |
| if (numbers[i] >= ((j + 1) * binSize)) { | |
| ++j; | |
| } | |
| res[j].push(numbers[i]); | |
| } | |
| return res; | |
| }; | |
| const pretty = (numbers, binSize) => { | |
| const maxDigitCount = digitCount(numbers.length * binSize); | |
| for(let i = 0; i < numbers.length; ++i) { | |
| const n = numbers[i].length; | |
| const name = i * binSize; | |
| const padding = maxDigitCount - digitCount(name); | |
| console.log(`${name}${nChar(padding, ' ')} | ${nChar(n, '#')}`); | |
| } | |
| }; | |
| const nChar = (n, char) => { | |
| if (n <=0 ) { | |
| return ''; | |
| } | |
| let res = char; | |
| while (--n) { | |
| res += char; | |
| } | |
| return res; | |
| }; | |
| const digitCount = (nb) => ('' + nb).length; | |
| //console.log(nChar(3, 'e')); | |
| const out = group( [1, 2, 3, 4, 5, 10, 11, 11], 5); | |
| //console.log(out); | |
| //console.log(digitCount(10)); | |
| pretty(out, 5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment