fork(5) download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Ideone
  6. {
  7. static int[] input = {1,2,3,4,5,-6,7,8,9,10,200,-1000,100,250,-720,1080,200,300,400,500,50,74};
  8.  
  9. public static void main(String[] args) {
  10. int[] two = new int[input.length/2];
  11. int[] one = new int[input.length - two.length];
  12.  
  13. int totalSum = 0;
  14. for(int i=0;i<input.length;i++){
  15. totalSum += input[i];
  16. if(i<one.length)
  17. one[i] = input[i];
  18. else
  19. two[i-one.length] = input[i];
  20. }
  21.  
  22. float goal = totalSum / 2f;
  23.  
  24. boolean swapped;
  25. do{
  26. swapped = false;
  27. for(int j=0;j<one.length;j++){
  28. int curSum = sum(one);
  29. float curBestDiff = Math.abs(goal - curSum);
  30. int curBestIndex = -1;
  31.  
  32. for(int i=0;i<two.length;i++){
  33. int testSum = curSum - one[j] + two[i];
  34. float diff = Math.abs(goal - testSum);
  35. if(diff < curBestDiff){
  36. curBestDiff = diff;
  37. curBestIndex = i;
  38. }
  39. }
  40.  
  41. if(curBestIndex >= 0){
  42. swapped = true;
  43. System.out.println("swapping " + one[j] + " and " + two[curBestIndex]);
  44. int tmp = one[j];
  45. one[j] = two[curBestIndex];
  46. two[curBestIndex] = tmp;
  47. }
  48. }
  49. } while(swapped);
  50.  
  51. System.out.println(Arrays.toString(one));
  52. System.out.println(Arrays.toString(two));
  53. System.out.println("diff = " + Math.abs(sum(one) - sum(two)));
  54. }
  55.  
  56. static int sum(int[] list){
  57. int sum = 0;
  58. for(int i=0;i<list.length;i++)
  59. sum += list[i];
  60. return sum;
  61. }
  62. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
swapping 1 and 500
swapping 2 and 1
swapping 3 and 2
swapping 4 and 3
[500, 1, 2, 3, 5, -6, 7, 8, 9, 10, 200]
[-1000, 100, 250, -720, 1080, 200, 300, 400, 4, 50, 74]
diff = 1