Please help the novice to solve the problem in Java: there are stones, each stone has its own weight, I want to distribute the stones into 2 piles so that the difference in the heaps would be minimal. This task should be solved by enumerating all the options.

I want to solve this problem by exhaustive search. Created one array with "Stones" arr and the second bit of the same dimension a . The approximate algorithm is as follows: if in a[1]=0 , then arr[1] in the first heap, if a[1]=1 then in the second. And so go through all the options. But I can not write all this in Java

Closed due to the fact that off-topic participants are Vladimir Martyanov , user207618, pavel , rjhdby , Denis 15 Oct '16 at 13:27 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - community spirit, pavel, rjhdby, Denis
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • And what exactly are the problems? - Vladimir Martyanov
  • one
    Please explain - do you want us to write a solution for you? This is not how they work. - user207618

2 answers 2

As an example:

 import java.util.*; public class StonesPile { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int[] pile = new int[a]; for (int i = 0; i < pile.length; i++) { pile[i] = sc.nextInt(); } Arrays.sort(pile); int pile1 = pile[pile.length - 1]; int pile2 = 0; for (int i = pile.length - 2; i >= 0; i--){ if (pile1 <= pile2){ pile1 += pile[i]; } else{ pile2 += pile[i]; } } System.out.println(Math.abs(pile1 - pile2)); } } 

    Bit array corresponds to a binary number. Looking through all the numbers from 0 to 1 * 2^n + 1 * 2^(n-1) + ... + 1 and including the corresponding elements, remembering the best result you can solve the problem.

    • You can find out if the kth element belongs to the array like this: (mask >> k) & 1, where mask is an encoded combination - Konstantin K