Search code examples
logic

How do I divide a number into an even number of groups?


If I'm given a number, and a number for how many groups I need to split the number in, how do I split it into as close of even number of chunks?

8 into 3 chunks -> 3, 3, 2

12 into 2 chunks -> 6, 6

9 into 2 chunks -> 4, 5

9 into 4 chunks -> 2, 2, 2, 3

11 into 5 chunks -> 2, 2, 2, 2, 3


Solution

  • This seems to work, more or less:

    int[] GetGroups(int number, int chunks) =>
        Enumerable
            .Range(0, chunks)
            .Select(x => number / chunks + (number % chunks > x ? 1 : 0))
            .ToArray();
    
    var inputs = new[]
    {
        new { n = 8, c = 3, },
        new { n = 12, c = 2, },
        new { n = 9, c = 2, },
        new { n = 9, c = 4, },
        new { n = 11, c = 5, },
    };
    
    foreach (var input in inputs)
    {
        Console.WriteLine($"{input.n} into {input.c} chunks -> {String.Join(", ", GetGroups(input.n, input.c))}");
    }
    

    That gives me:

    8 into 3 chunks -> 3, 3, 2
    12 into 2 chunks -> 6, 6
    9 into 2 chunks -> 5, 4
    9 into 4 chunks -> 3, 2, 2, 2
    11 into 5 chunks -> 3, 2, 2, 2, 2