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
Well I've come up with something "just for fun".
It goes incrementally from minimum
to number
and populates an array with N
sections using modulo and random.
See the jsFiddle here.
It won't work as expected if there are too many sections for this number. (ie number < N(N+1)/2
)
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<List<Integer>> computeRepartitionNumber(int number_to_decompose, int number_of_subnumbers, int threshold_number) {
List<List<Integer>> resultRec = new ArrayList<>();
if (number_of_subnumbers == 1) {
List<List<Integer>> resultEnd = new ArrayList<>();
ArrayList<Integer> 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<List<Integer>> partialRec = computeRepartitionNumber(remain, number_of_subnumbers - 1, threshold_number);
for(List<Integer> subList : partialRec){
subList.add(i);
}
resultRec.addAll(partialRec);
}
return resultRec;
}
public static void main(String[] args) {
List<List<Integer>> superlist = computeRepartitionNumber(5, 2, 1);
System.out.println(superlist.size());
System.out.println(superlist);
}
}
Here's an algorithm:
N
by m
where N
is your number and m
is the number of subsections.N
. At this point if N
was 50 and m
was 7, you'd have 8, 7, 7, 7, 7, 7, 7m-1
, stepping by 2, and add a random number between -(currentValue-base)
and currentValue-base
. Add the inverse of that number to its neighboring bucket. If you have an odd number of buckets, then on the last bucket instead of adding the inverse of that number to its neighboring bucket, add it to all of the other buckets in a distributed manner similar to steps 2 and 3 above.Performance:
Step 1 is O(1)
, Steps 2, 3, and 4 are O(m)
, so overall it's O(m)
.