The problem need not to be sequentially-in-time coded. Make a centrally procedure to solve this knapsack problem, but do not code it yet. Then sort the results, and give the results.
Now should you fail solving, say for time-out, there still is an approach done.
The problem could be further simplified, by using the sum of the array arr
, divide it by 2, and search a subarray of this half-sum.
The problem poses some weird restrictions: arr
keeps an even number of values (8), the two resulting arrays should have the same even number of values (both 4).
To select to which subarray the ith value belongs is binary.
So start with a sorted array, cut the solutions when the half is reached.
You could start with 00001111 (half the bits 1) which probably is too big, the following bits would be 00010111, 00011011, 00011101, 00011110, 00101110, ...
Easier would probably simple recursion, with a count upto the half:
// Array arr sorted decreasingly to have less values to try out.
boolean solve(Set<Integer> selectedNumbers, int selectedSum, int index) {
if (selectedNumbers.size() >= arr.length/2) {
return sum == arrSum/2;
}
if (index > arr.length) {
return false;
}
boolean solved = false;
// First case: add array element at this index:
if (selectedSum + arr[index] <= arrSum/2) {
seplectedNumbers.add(arr[index]);
arrSum += arr[index];
solved = solve(selectedNumbers, arrSum, index + 1);
if (!solved) {
// No remove(int index), so remove an Object, Integer.
selectedNumbers.remove(Integer.valueOf(arr[index]));
arrSum -= arr[index];
}
}
// Second case: do not add array element at this index:
if (!solved) {
solved = solve(selectedNumbers, arrSum, index + 1);
}
return solved;
}
The above of course is a brute force solution. If you are into Operations Research you might find a distribution of those numbers to start with (like the bits mentioned). But time needed and for me my meager math knowledge would prevent that.
When solved you might put in a remark should you know a faster solution.