Jac*_*ade 5 javascript arrays underscore.js
有没有办法将数字列表分组为带下划线的数字区间?
// Input:
var arr = [0,1,2,8];
var interval = 3;
// Output:
// There are 3 numbers from 0 to <3
// There are 0 numbers from 3 to <6
// There is 1 number from 6 to <9
// Returns [3, 0, 1]
Run Code Online (Sandbox Code Playgroud)
我注意到一些解决方案不会测试更大的值.尝试第二个测试用例:
var arr = [110,113,116,119];
Run Code Online (Sandbox Code Playgroud)
在普通的 Javascript 中,您只需将数字除以间隔并使用整数部分进行分组。
有数组且缺少间隔。
function getHistogram(array, interval) {
var bin,
result = [];
array.forEach(function (a) {
var key = Math.floor(a / interval);
if (!bin) {
bin = [key, key];
result[0] = 0;
}
while (key < bin[0]) {
--bin[0];
result.unshift(0);
}
while (key > bin[1]) {
++bin[1];
result.push(0);
}
++result[key - bin[0]];
});
return result;
}
console.log(getHistogram([0, 1, 2, 8], 3));
console.log(getHistogram([110, 113, 116, 119], 3));
console.log(getHistogram([15, 10, 26], 3));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
有对象且缺少间隔。
function getHistogram(array, interval) {
var bin,
result = {};
array.forEach(function (a) {
var key = Math.floor(a / interval);
if (!bin) {
bin = [key, key];
result[key] = 0;
}
while (key < bin[0]) {
result[--bin[0]] = 0;
}
while (key > bin[1]) {
result[++bin[1]] = 0;
}
++result[key];
});
return result;
}
console.log(getHistogram([0, 1, 2, 8], 3));
console.log(getHistogram([110, 113, 116, 119], 3));
console.log(getHistogram([15, 10, 26], 3));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)