How do I create a distribution group of a range of numbers by a given number of groups

2.2k Views Asked by At

In Javascript, if I have a range of numbers, say 0-10000. like this:

var min = 0;
var max = 10000;

and I want to split this range into a number of buckets by a input:

var buckets = 5;

in this case, I want to return an array of numbers that splits up this range: ie. the resulting numbers would be: 0, 2000, 4000, 6000, 8000, 10000

if I said 10 buckets, the numbers would be 0, 1000, 2000, etc....

My issue is if I have 8 buckets, 12 buckets 32 buckets.... How would I do this in javascript? Thanks.

3

There are 3 best solutions below

3
On BEST ANSWER
var dif = max - min;
var a = dif/bucked;

for (var i=min; i<=max;i=i+a){
  i;
}
1
On
var min = 0,
    max = 1000,
    buckets = 8,
    i, array = [];

for (i = min; i <= max; i += (max - min) / buckets) {
    array.push(i);
}
1
On

I had the same problem but also needed to create a string literal to describe each bucket, like a 'from-to' string. Altering Seva Arkhangelskiy's answer, this is the function I came up with. It returns the limit range for each bucket, but also a proper name for the bucket.

function distribute (max, buckets) {
    var arr = [], rpt = max / buckets, groupLiteral_low;
    for (var i = 0; i < max; i += rpt) {
        if (Math.ceil(i) != i || i==0) {
            groupLiteral_low = Math.ceil(i);
        } else {
            groupLiteral_low = Math.ceil(i)+1;
        }
        arr.push({
            "limit": (Math.floor(rpt+i)),
            "literal": groupLiteral_low + "-" + (Math.floor(rpt+i))
        });
    }
    return arr; 
}

For example, distribute(100,3) will return ​

0: Object { limit: 33, literal: "0-33" }​
1: Object { limit: 66, literal: "34-66" }​
2: Object { limit: 100, literal: "67-100" }