Javascript中的简单直方图算法 [英] Simple histogram algorithm in Javascript
本文介绍了Javascript中的简单直方图算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建直方图算法。我正在按照此处提供的解决方案。
Im creating a histogram algorithm. Im following the solution offered here.
我想简单地计算每个值出现的次数。
I want to simply count the number of times each value has occurred.
但是我不能完全理解算法。我的代码是:
However I cant quite get the algorithm right. My code is:
var values = [2, 4, 6, 3, 3];
var val_max = 6;
var val_min = 2;
var num_bins = parseInt(val_max - val_min + 1);
console.log('num_bins is ', num_bins);
var bin_width = (val_max-val_min)/num_bins;
console.log('bin_width is ', bin_width);
var to_plot = [];
for (var i = 0; i < num_bins; i++) {
to_plot.push(0);
}
for (var x = 0; x < values.length; x++) {
var bin_idx = parseInt((values[x] - val_min) / bin_width);
to_plot[bin_idx] = to_plot[bin_idx] + 1;
}
console.log('to_plot is ', to_plot);
如果您查看控制台日志,则会看到:
If you look at the console logs, you'll see:
to_plot is [1, 2, 1, 0, 0, NaN]
我希望最后一个索引为 1。但是问题是值接近最大值, bin_idx
超出范围。我该如何调整才能获得以下结果?
I want that last index to be "1". But the problem is for values close the the maximum value, bin_idx
is out of range. How can I tweak this so that I would get the following results?
to_plot is [1, 2, 1, 0, 1]
jsfiddle是此处。
The jsfiddle is here.
推荐答案
这就是我要做的事情:
const data = [2, 4, 6, 3, 3];
print(histogram(data, 1)); // [1, 2, 1, 0, 1]
print(histogram(data, 2)); // [3, 1, 1]
print(histogram(data, 3)); // [4, 1]
print(histogram(data, 4)); // [4, 1]
print(histogram(data, 5)); // [5]
function histogram(data, size) {
let min = Infinity;
let max = -Infinity;
for (const item of data) {
if (item < min) min = item;
else if (item > max) max = item;
}
const bins = Math.ceil((max - min + 1) / size);
const histogram = new Array(bins).fill(0);
for (const item of data) {
histogram[Math.floor((item - min) / size)]++;
}
return histogram;
}
function print(x) {
console.log(JSON.stringify(x));
}
这也适用于非整数值。
这篇关于Javascript中的简单直方图算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文