Search code examples
javasortingmatharraylistmathematical-optimization

Method that returns all permutation given some maximum and minimum criteria


Need to build this method, that probably will use some recursion, with no success, that once given total and maximum and the minimum value for each element return all possible lists whose sum of the elements are the total value.

Ex

Input:
Total: 25
Maximum value per element in array:5
Minimum value per element in array:3

Output: 

[5,5,5,5,5] [4,4,4,4,4,5] [3,3,4,4,4,4,3] [3,3,4,4,4,4,3] [3,3,3,4,4,4,4] [3,3,3,3,4,4,5]
....

Solution

  • Pseudocode:

    void makesum(lst, int asum, int amin, int amax):
        if (asum == 0) {
            print(lst.ToString());
        } 
        else {
            for (int i=amin; i <= min(asum, amax); i++) {
                makesum(lst.add(i), asum - i, amin, amax);
            }
       }
    
    makesum(empty_array, 15, 3, 5)
    

    (working Python version for reference)