Algorithm to evenly distribute values into containers?

前端 未结 2 869
一生所求
一生所求 2021-01-04 11:03

Does anyone know a way to evenly distribute numbers into a set number of containers, making sure that the total values of the containers are as even as possible?

EDI

2条回答
  •  星月不相逢
    2021-01-04 11:41

    Interesting. This C program seems to give the expected result so far. It starts with sorting the data, then for n containers, immediately stores the n highest numbers in each one. (You can omit that step, actually.) Then, from largest remaining number to smallest, it finds the container where adding that number makes the smallest difference to the optimal average. Because this runs from high to low, each number is placed into the optimal container -- all other numbers are lower, so the difference for them would even be bigger.

    #include 
    #include 
    #include 
    #include 
    
    int sort_numeric (const void *a, const void *b)
    {
        return *((int *)a) - *((int *)b);
    }
    
    int main (int argc, char **argv)
    {
        int list[] = { 10, 30, 503, 23, 1, 85, 355 };
        int i,j, nnumber, ncontainer, total, avgPerContainer, nextError, smallestError, containerForSmallest;
        int *containers, *errors;
    
        ncontainer = 3;
    
        nnumber = sizeof(list)/sizeof(list[0]);
    
        qsort (list, nnumber, sizeof(list[0]), sort_numeric);
    
        containers = (int *)malloc(ncontainer * sizeof(int));
        for (i=0; i=0; i--)
        {
            smallestError = INT_MAX;
            containerForSmallest = 0;
            for (j=0; j

提交回复
热议问题