Monday, 27 January 2014

JAVA: Divide an int array in to two arrays so that the sum of elements in each subarray is equal , if division is not possible display a error message to the user.

package PACKAGE1;

import java.io.*;
import java.util.Arrays;

public class programRareMile {

 public static void main(String args[]) throws NumberFormatException,
   IOException {

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("enter the no. of elements to enter");
  int n = Integer.parseInt(br.readLine());
  int x[] = new int[n];
  System.out.println("Enter " + n + " elements");
  int half;
  int sum = 0;

  for (int i = 0; i < n; i++) {

   x[i] = Integer.parseInt(br.readLine());
  }

  
  for (int i = 0; i < n; i++) {
   sum = sum + x[i];
  }

  if (sum % 2 != 0) {
   System.out.println("the sum is odd and cannot be divided");
   System.out.println("The sum is " + sum);
  } else {
   boolean div = false;
   half = sum / 2;
   int sum1 = 0;
   for (int i = 0; i < n; i++) {

    sum1 = sum1 + x[i];
    if (sum1 == half) {
     System.out.println("array can be divided");
     div = true;
     break;
    }

   }

   if (div == true) {
    int t = 0;
    int[] array1 = new int[n];
    int count = 0;
    for (int i = 0; i < n; i++) {
     t = t + x[i];
     if (t <= half) {
      array1[i] = x[i];
      count++;
     }
    }
    array1 = Arrays.copyOf(array1, count);
    int array2[] = new int[n - count];
    int k = 0;
    for (int i = count; i < n; i++) {
     array2[k] = x[i];
     k++;
    }
    System.out.println("The first array is ");
    for (int m : array1) {

     System.out.println(m);
    }
    System.out.println("The second array is ");
    for (int m : array2) {

     System.out.println(m);
    }
   } else {
    System.out.println("array cannot be divided");
   }
  }
 }

}


No comments:

Post a Comment