I have an interval [0; max]
and I want to split it into a specific number of sub-intervals. For this, i wrote a function called getIntervalls(max, nbIntervals)
where max
is the max element in my first interval and nbIntervals
is the number of expected sub-intervals.
For example:
getIntervalls(3, 2)
should return [[0,1], [2,3]]
, getIntervalls(6, 2)
should return [[0,3], [4,6]]
,getIntervalls(8, 3)
should return [[0,2], [3,5], [6,8]]
,getIntervalls(9, 3)
should return [[0,3], [4,7], [8,9]]
,Here is my function:
function getIntervalls(max, nbIntervalls) {
var size = Math.ceil(max / nbIntervalls);
var result = [];
if (size > 1) {
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size: max;
result .push([inf, sup]);
}
} else {
result.push([0, max]);
}
return result;
}
console.log(JSON.stringify(getIntervalls(7, 2)));
It work properly, and shows this output:
[[0,4],[5,7]]
When I change the parameters to 7 and 3, it shows:
[[0,3],[4,7],[8,7]]
instead of
[[0,2],[3,5],[6,7]]
Would anyone can help me? Thank you in advance. An ES6 syntax will be appreciated! :)
You need to use Math.round()
for take the nearest integer of the decimal number of the size
of interval. Also, you need to descrease a one the max
for size
calculation to take account of the effective number of interval.
Here the modification of your code :
function getIntervalls(max, nbIntervalls) {
var size = Math.round((max-1) / nbIntervalls);
var result = [];
for (let i = 0; i < nbIntervalls; i++) {
var inf = i + i * size;
var sup = inf + size < max ? inf + size: max;
result.push([inf, sup]);
if(inf >= max || sup >= max)break;
}
return result;
}
Note that it respect the wanted number of interval, so some case of couple of number can result [..., [n-2,n-1], [n,n]]
.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With