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.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: