Divide an integer into evenly distributed groups with an ES6 generator

Say you’d like to divide an integer, e.g. 20, into equal parts of 3 and distribute any remainder equally across the groups. The result of such an operation would be the following 3 integers:

7,7,6

20 can be divided into 3 equal parts of 6 and we have a remainder of 20 – 6 * 3 = 2. 2 is then added as 1 and 1 to the first two groups of 6. The result is a more or less equal distribution of the starting integer.

The following ES6 generator function will perform just that:

let distributeInteger = function* (total, divider) {
  if (divider === 0) {
    yield 0
  } else {
    let rest = total % divider
    let result = total / divider
    
    for (let i = 0; i < divider; i++) {
      if (rest-- >0) {
        yield Math.ceil(result)
      } else {
        yield Math.floor(result)
      }
    }
  } 
}

Usage:

let groups = []
for (let member of distributeInteger(20, 3)) {
  groups.push(member)
}

groups will have the expected elements:

[7,7,6]

View all posts related to JavaScript here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: