首页 > 解决方案 > 为数组中的数字创建直方图

问题描述

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

在此处输入图像描述

标签: javascript

解决方案


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

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>


推荐阅读