JavaScript-从给定数组中打印直方图 [英] JavaScript - Print a Histogram from a given array
本文介绍了JavaScript-从给定数组中打印直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//给定整数数组[2,1,2,101,4,95,3,250,4,1,2,2,7,98,123,99,...]
// Given an array of integers [2, 1, 2, 101, 4, 95, 3, 250, 4, 1, 2, 2, 7, 98, 123, 99, ...]
我正在尝试编写一个函数(具有线性运行时复杂度)来打印以下带有类似直方图的"xxx"的表格输出(输出应与下面的示例输出紧密匹配,包括"99+"捕获所有大于99的数字的计数):
I'm trying to Write a function (with linear run-time complexity) to print the following tabular output with ‘xxx' that resembles a histogram (the output should closely match the sample output below, including "99+" to capture the count for all numbers > 99):
Num | count
1 | xx
2 | xxxx
3 | x
4 | xx
98 |X99 |X99+ |xxx
98 | x 99 | x 99+| xxx
推荐答案
const dict = {}; // Empty dictionary
var min = Number.MAX_VALUE;
const maxRange = 5; // 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];
// 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;
}
这篇关于JavaScript-从给定数组中打印直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文