Answer the question
In order to leave comments, you need to log in
How to solve a logical math problem in PHP?
Hello. Help me choose a solution algorithm.
Task:
There is an array with N elements (natural random numbers from 1 to 3000).
It is necessary to group the elements of the array into 8 groups so that the sum of the elements in each group is as close as possible to the sum of the elements in any group. (As close as possible to equality among themselves)
Ideally, in the problem of n-groups. Eight is in my particular example.
Answer the question
In order to leave comments, you need to log in
You can try:
1. Find N
2. Calculate the sum of all elements
3. Find the average of 8 groups
4. Sort in ascending order
5. Start filling each array until the sum in the current group is less than the average (point 3)
1. Find the sum of all the numbers, and divide by 8, get the target value, denote it O
2. Going from the beginning of the source array, fill the first array of the result with numbers until the addition of the next number gives the array sum greater than O
3. You repeat the previous step for the remaining seven arrays.
4. If there are numbers left in the source array, add them one by one to the output arrays, starting from the first one.
5. (Here, for convenience, you can sort the resulting arrays)
6. You select two arrays - one with the largest excess of O, the other with the largest shortage of O.
7. In the first (of these two) arrays, you select the maximum number that is less than the excess , and transfer it to the second of these two arrays.
8. Repeat steps 6 and 7 until it turns out that there is no number to transfer.
9. End.
I think it should work.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question