Here's the problem:
You have N (N represents the number of numbers that you have) numbers. Divide them in 2 groups in such way that the difference between sums of the numbers in the groups is minimal.
Examples:
5 // N
1, 9, 5, 3, 8 // The numbers
The difference is 0 if we put 1, 9 and 3 in Group A and 5 and 8 in Group B.
I think first I should calculate the sum of all numbers and divide it by 2. Then to check ever possible combination of numbers, whose sum is not higher than half of the sum of all numbers. After I do this I will choose the biggest number and print out the groups.
I have problem with going through all combinations, especialy when N is big numbers. How can I run through all combinations?
Also i think a little bit differently, I will group the numbers in descending order and i'll put the biggest number in Group A and lowest in Group B. Then I do the other way around. This works with some of the numbers, but sometimes it doesn't show the optimal grouping. For example:
If I use the previous example. Arrange the number in descending order.
9, 8, 5, 3, 1.
Put the biggest in Group A and lowest in Group B.
Group A: 9
Group B: 1
Other way around.
Group A: 9, 3
Group B: 1, 8
And so on. If in the end i have only one number I'll put it in the group with lower sum. So I finally will get:
Group A: 9, 3
Group B: 1, 8, 5
This isn't the optimal grouping because the difference is 2, but with grouping in different way the difference can be 0, as I showed.
How can I get optimal grouping?
CODE:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int convertToBinary(int number) {
int remainder;
int binNumber = 0;
int i = 1;
while(number!=0)
{
remainder=number%2;
binNumber=binNumber + (i*remainder);
number=number/2;
i=i*10;
}
return binNumber;
}
int main()
{
int number, combinations, sum = 0;
double average;
cin >> number;
int numbers[number];
for(int i = 0; i<number; i++)
{
cin >> numbers[i];
sum += numbers[i];
}
if(sum%2 == 0)
{
average = sum/2;
}
else
{
average = sum/2 + 0.5;
}
combinations = pow(2,number-1);
double closest = average;
for(int i = 0; i<=combinations;i++)
{
int rem;
int temp_sum = 0;
int state = convertToBinary(i);
for(int j = 0; state!=0; j++)
{
int rem =state%10;
state = state/10;
if(rem == 1)
{
temp_sum = temp_sum + numbers[j];
}
}
if(abs(average-temp_sum)<closest)
{
closest = abs(average-temp_sum);
if(closest == 0)
{
break;
}
}
}
cout << closest*2;
return 0;
}