Evenly distribute number into array of n elements with equal values

Viewed 163

I'm trying to divide x into y parts and they should be as evenly distributed as possible.

As an example:
if x = 5 and y = 3 I'd like to have arr = [1, 2, 2].
The solution I came up with basically prints [1, 1, 3] which isn't as evenly as possible distributed.

int *arr= (int *)malloc(y* sizeof(int));

for (int i = 0; i < y; i++)
    {
        arr[i] = x / y;

        if (i == nrThreads - 1)
        {
            arr[i] = x / y+ x % y;
        }
        
        printf("%d ",arr[i]);
    }

The order of the array entries does not matter. It can be either of the three:
[1, 2, 2], [2, 1, 2], [2, 2, 1]

1 Answers

I simplified to only printing the numbers you want.
First print x/y+1 as often as you have remainder (I.e. modulo), then print for the rest of the needed numbers only x/y.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 5;
    int y = 3;
    int i=0;
    
    for (; i < x%y; i++)
    {
        printf("%d ", x/y+1);
    }
    for (; i < y; i++)
    {
        printf("%d ", x/y);
    }
    printf("\n");

    return 0;
}

Output:

2 2 1 
Related