I am trying to generate two arrays from one big array, of which the sum of the 2 array's elements are as close to equal or equal to each other if possible, or one array summed up minus the second array summed up will be as close to zero as possible. I start with int array of 30.
It says that the lowest possible combination of one array minus the other is 239 which I know is not true. Also this needs to run in under ten minutes. Any help would be greatly appreciated.
Find the mean of the array:
16.1
Find the median:
9
Take the largest of the 2 and set it as your pivot point
split the array at the point where values are above the pivot and values are below the pivot and you get these 2 arrays:
[1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 6, 7, 8, 9, 9, 12, 13, 14, 14, 15] and [18, 19, 21, 23, 33, 35, 56, 67, 73]
Now you start the balancing act:
Get the sum of the 2 arrays and start swapping values to make their sums as close to equal as possible
Start with making the array with the larger sum as close as possible to the array with the smaller sum
If they are still not equal, and the smaller array is now larger try using values from that one to balance the other one. This should get them as close as possible to each other
EDIT:
Initial sum of both arrays:
138 and 345
After first balancing, I got
252 and 231
[1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 6, 7, 8, 9, 9, 12, 13, 14, 14, 15, 18, 19, 21, 23, 33] and [35, 56, 67, 73]
After second I get:
241 and 242
[3, 3, 4, 5, 5, 6, 7, 8, 9, 9, 12, 13, 14, 14, 15, 18, 19, 21, 23, 33] and [35, 56, 67, 73, 1, 1, 2, 2, 2, 3]
EDIT 2:
Note this method is not proven to work for other problems of this type, I even looked up this particular problem on Google and turns out it is NP-hard.