Search code examples
algorithmcombinationspermutationpseudocode

Algorithm for exhaustive incremental distribution into a fixed number of slots


I have a simulation that I'm building and I'm in need of an algorithm to distribute/redistribute a fixed total floating point value into 10 different "slots" by set increments and repeat the process until all permutations have been simulated. I know I have to set a bound because I am working with floating point values.

In the simplest case, I'd have my 10 slots and a total value of 10.0 to distribute, with the smallest increment being 1.0, so I'm working purely with integers. So I'd like to be able to run the simulation from this point:

| 10 |  0 |  0 |  0 |  0 |  0 |  0 |  0 |  0 |  0 |

To this point:

|  0 |  0 |  0 |  0 |  0 |  0 |  0 |  0 |  0 | 10 |

With ever possible permutation that sums to 10.0 in between.

I know I can do the math to calculate the number of permutations, I'm just not sure how to devise an algorithm to achieve this. Any thoughts?


Solution

  • I don't know what your language of choice is, but here is a solution in Java.

    public static void main(String[] args) {
        slots(4, 0, new int[3]);
    }
    
    private static void slots(int sum, int index, int[] array) {
        if (index == array.length - 1) {
            array[index] = sum;
            // Do something with the array here.
        } else {
            for (int i = 0; i <= sum; i++) {
                array[index] = i;
                slots(sum - i, index + 1, array);
            }
        }
    }
    

    When I replace the comment by System.out.println(Arrays.toString(array)); the output is

    [0, 0, 4]
    [0, 1, 3]
    [0, 2, 2]
    [0, 3, 1]
    [0, 4, 0]
    [1, 0, 3]
    [1, 1, 2]
    [1, 2, 1]
    [1, 3, 0]
    [2, 0, 2]
    [2, 1, 1]
    [2, 2, 0]
    [3, 0, 1]
    [3, 1, 0]
    [4, 0, 0]