Guest User

Untitled

a guest
Apr 25th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. package lesson04.home_work.level2;
  2.  
  3. public class BalanceChecker {
  4. public static void main(String[] args) {
  5. System.out.println(isBalanced(new int[]{1, 1, 1, 2, 1}));
  6. System.out.println(isBalanced(new int[]{2, 1, 1, 2, 1}));
  7. System.out.println(isBalanced(new int[]{1, 1}));
  8. try {
  9. System.out.println(isBalanced(new int[]{}));
  10. }catch (IllegalArgumentException e){
  11. System.out.println("array is empty");
  12. }
  13. }
  14.  
  15. public static boolean isBalanced(int[] array) {
  16. if (array.length==0) throw new IllegalArgumentException();
  17. if (array.length==1) return false;
  18.  
  19. for (int i = 1; i < array.length; i++) {
  20. int sumLeft = 0;
  21. for (int j = 0; j < i; j++) {
  22. sumLeft+=array[j];
  23. }
  24. int sumRight = 0;
  25. for (int j = i; j < array.length; j++) {
  26. sumRight+=array[j];
  27. }
  28. if (sumLeft==sumRight) return true;
  29. }
  30. return false;
  31. }
  32. }
  33. //output
  34. // {1, 1, 1, 2, 1} => true
  35. // {2, 1, 1, 2, 1} => false
  36. // {1, 1} => true
  37. // {} => array is empty
Add Comment
Please, Sign In to add comment