javascript - 为数组中的数字创建直方图
问题描述
为数组中的数字创建直方图,其中 x 轴将表示特定大小的存储桶,y 轴将使用 javascript 指示有多少数字属于特定存储桶
我找到了一个解决方案,但输出在不同的轴上。
const dict = {}; // Empty dictionary
var min = Number.MAX_VALUE;
const maxRange = 15; // elements above maxRange will be clubbed in the same range.
//var arr = [2, 1, 2, 101, 4, 95, 3, 250, 4, 1, 2, 2, 7, 98, 123, 99];
const arr = [1, 2, 5, 3, 2, 2, 1, 5, 5, 6, 7, 1, 8, 10, 11, 12, 12];
// iterate the array and set and update the counter in map
arr.forEach(function (num) {
min = Math.min(min, num); // find min
if (num > maxRange) {
num = maxRange + 1;
}
dict[num] = dict[num] ? dict[num] + 1 : 1;
});
console.log("Num | Count");
// Print the occurrences per item in array starting from min to max
while (min <= maxRange + 1) {
if (!dict[min]) { // print only those numbers which are defined in dictionary
min++;
continue;
}
var xArr = []
var range = dict[min];
for (i = 0; i < range; i++) {
xArr.push('x');
}
var disp = (min <= maxRange) ? (min + " | " + xArr.join("")) : (maxRange + "+ | " + xArr.join(""));
console.log(disp);
min = min + 1;
}
我期望 x 轴上特定大小的桶的输出和 y 轴上的计数。
解决方案
您可以采用一个函数,该函数使用直方图生成给定对象的动态输出。
function print(histogram, captionTop = 'Count', captionBottom = 'Values') {
var keys = Object.keys(histogram),
maxKey = keys[keys.length - 1],
maxValue = Math.max(...Object.values(histogram)),
slot0 = Math.max(captionTop.length, captionBottom.length),
slot = Math.max(...keys.map(k => histogram[k].toString().length), (maxKey - 1).toString().length + 1) + 3,
line,
result = '';
do {
line = (maxValue === +keys[0] ? captionTop : '').padEnd(slot0);
for (let k in histogram)
line += (histogram[k] >= maxValue ? ''.padStart(slot - 1) + 'X' : '').padEnd(slot + 1);
result += line + '\n';
} while (--maxValue)
line = ''.padEnd(slot0, '-');
for (let k in histogram) line += ' ' + ''.padStart(slot, '-');
result += line + '\n';
line = captionBottom.padEnd(slot0);
for (let k in histogram) {
if (k === maxKey) k = '+' + (maxKey - 1);
line += (''.padStart(slot - k.length) + k).padEnd(slot + 1);
}
result += line;
return result;
}
document.getElementById('out').innerHTML = print({ 1: 3, 2: 3, 3: 1, 5: 3, 6: 7 });
<pre id="out"></pre>
推荐阅读
- r - 基于列向量的匹配
- javascript - 在 react-table-2 的同一列中显示名字和姓氏
- angular - 主从角度材质示例
- node.js - 如何使用 cPanel 在 GoDaddy VPS 上部署 Node JS 应用程序?一步一步的过程将受到高度赞赏
- hibernate - Hibernate:当没有物理列或值用于区分实例时,鉴别器列如何工作?
- jquery - 如何对数据表进行排序(bDestroy)并添加合并单元格功能
- reactjs - 如何更改箭头并在反应选择中放置一个三角形而不是它,当悬停改变颜色时?
- reactjs - 如何从 Chrome 开发工具源中隐藏代码?
- java - 我应该如何在现有父级的基于一对多注释的映射中执行更新操作?
- javascript - 避免使用带有 React+Redux 的 array.map 重新渲染组件