I have an interval [0; max] [0; max] , and I want to break it into a certain number of sub-intervals. To do this, I wrote a function called getIntervalls(max, nbIntervals) , where max is the maximum element in my first interval, and nbIntervals is the number of expected auxiliary intervals.
For instance:
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 works correctly 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
[[0,2],[3,5],[6,7]]
Can anybody help me? Thank you in advance. ES6 syntax will be appreciated! :)
Laiso source share