Divide an integer into groups with C# .NET
January 19, 2017 2 Comments
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.
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.
Vielen Dank Michael!
Gruss,
Andras