Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a range of number to a specific number of intervals

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! :)

like image 405
Laiso Avatar asked Mar 08 '18 14:03

Laiso


1 Answers

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!

like image 115
Mahefa Avatar answered Oct 20 '22 00:10

Mahefa