gpt4 book ai didi

javascript - 为数组中的数字创建直方图

转载 作者:行者123 更新时间:2023-11-28 03:32:55 25 4
gpt4 key购买 nike

为数组中的数字创建直方图,其中 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 轴上输出计数。

enter image description here

最佳答案

您可以采用一个函数,通过直方图生成给定对象的动态输出。

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>

关于javascript - 为数组中的数字创建直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58005556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com