Divide an integer into groups with C# .NET

Imagine that we have an integer and we want to divide it into equal groups of another integer and put any remainder to the end of the group. E.g. if we want to divide 100 into groups/batches of at most 15 then we’ll have the following array of integers:

15, 15, 15, 15, 15, 10

The following C# function will perform exactly that function:

private IEnumerable<int> BatchInteger(int total, int batchSize)
{
	if (batchSize == 0)
	{
		yield return 0;
	}

	if (batchSize >= total)
	{
		yield return total;
	}
	else
	{
		int rest = total % batchSize;
		int divided = total / batchSize;
		if (rest > 0)
		{
			divided += 1;
		}

		for (int i = 0; i < divided; i++)
		{
			if (rest > 0 && i == divided - 1)
			{
				yield return rest;
			}
			else
			{
				yield return batchSize;
			}
		}
	}
}

If the batch size is 0 then we return 0. Also if the batch size is is equal to or bigger than the total then we return the batch size. Otherwise we keep returning the batch size until the remainder is smaller than that. At which point we return the remainder.

Usage:

var batch = BatchInteger(100, 15);
foreach (int item in batch)
{
	Console.WriteLine(item);
}

The result is exactly as we expect:

15
15
15
15
15
10

View all various C# language feature related posts here.

Advertisement

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

2 Responses to Divide an integer into groups with C# .NET

  1. Michael says:

    Hi, it seems you have lost one 15 while copying it. Code works fine.
    I’m a big fan of your great knowledge-project, I learn a lot. Thank you very much.

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 )

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: