Divide an integer into groups with C#

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 start integer.

The following function will perform just that:

public static IEnumerable<int> DistributeInteger(int total, int divider)
{
	if (divider == 0)
	{
		yield return 0;
	}
	else
	{
		int rest = total % divider;
		double result = total / (double)divider;

		for (int i = 0; i < divider; i++)
		{
			if (rest-- > 0)
				yield return (int)Math.Ceiling(result);
			else
				yield return (int)Math.Floor(result);
		}
	}
}

Call it as follows:

List<int> test = DistributeInteger(20, 3).ToList();

“test” will include 7,7,6 as expected.

View all various C# language feature related posts here.

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

3 Responses to Divide an integer into groups with C#

  1. martino's avatar martino says:

    Very interesting.
    Please let to share it on Google+.

  2. Wolfgang Kinkeldei's avatar Wolfgang Kinkeldei says:

    Thanks for your post. I had exactly the same problem some time ago. My solution is similar but only uses integer arithmetic by subsequentially dividing the remaining count by the decreasing number of remaining parts.

    https://github.com/wki/DevOpenSpace-2016-Akka.NET/blob/master/PiCalculator/PiCalculator/Actors/Master.cs#L91-L105

Leave a comment

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

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