Split number into sum components

后端 未结 9 2364
-上瘾入骨i
-上瘾入骨i 2021-02-12 18:07

Is there an efficient algorithm to split up a number into N subsections so that the sum of the numbers adds up to the original, with a base minimum? For example, if

9条回答
  •  遥遥无期
    2021-02-12 18:46

    Here is a java example of code creating the requested repartition of numbers. It is recursive approach, we decompose the problem into 2 subproblems : if we want to decompose a number in to a sum of components amongst n baskets, then we try to consider a subnumber at a time, and for each of them delegate the finding out of the remaining decomposition to the recursive call for the repartition amongst (n-1) baskets. The requested threshold is considered when processing a particular subnumber (in the for loop).

    import java.util.ArrayList;
    import java.util.List;
    
    public class TestFigures {
    
        public static List> computeRepartitionNumber(int number_to_decompose, int number_of_subnumbers, int threshold_number) {
            List> resultRec = new ArrayList<>();
    
            if (number_of_subnumbers == 1) {
                List> resultEnd = new ArrayList<>();
                ArrayList unitary = new ArrayList<>();
                resultEnd.add(unitary);
                unitary.add(number_to_decompose);
                return resultEnd;
            }
    
            for (int i = threshold_number; i <= number_to_decompose-threshold_number; i++) {
                int remain = number_to_decompose - i;
                List> partialRec = computeRepartitionNumber(remain, number_of_subnumbers - 1, threshold_number);
                for(List subList : partialRec){
                    subList.add(i);             
                }
                resultRec.addAll(partialRec);
            }
            return resultRec;
    
        }
    
        public static void main(String[] args) {
            List> superlist = computeRepartitionNumber(5, 2, 1);
            System.out.println(superlist.size());
            System.out.println(superlist);
    
        }
    
    }
    

提交回复
热议问题