In: Computer Science
(JAVA)
Balanced
Class diagram:
Balanced
+ swing(int[] a) : boolean
For this exercise, you will have to implement the class diagram
above. Basically, the objective of this exercise is to develop the
class and the previous method, in such a way that it tells us if an
array is balanced or not.
We say that an array is balanced if the sum of the elements belonging to the first half of the array (not including the element in the middle), and the sum of the elements belonging to the second half of the array (not including the element in the middle) They are equal.
Example 1: the balance method receives the array [1,2,3,4,2]
The method returns false
Example 2: the balance method receives the array [1,2,78,3,0]
The method returns true
TIP: for this exercise, ONLY odd arrangements will be made.
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== public class Balanced { public boolean swing(int[] a) { if (a == null) return false; if (a.length <= 1) return true; int front =0; int rear = a.length-1; int firstHalfSum = 0, secondHalfSum = 0; while ((rear-front)!=1 &&(rear-front)!=0){ firstHalfSum+= a[front++]; secondHalfSum+=a[rear--]; } return firstHalfSum==secondHalfSum; } public static void main(String[] args) { Balanced balanced = new Balanced(); System.out.println("balanced.swing(new int[]{1,2,3,4,2}) = " + balanced.swing(new int[]{1, 2, 3, 4, 2})); System.out.println("balanced.swing(new int[]{1,2,7,8,3,0}) = " + balanced.swing(new int[]{1, 2, 7, 8, 3, 0})); System.out.println("balanced.swing(new int[]{1,2,3,4,5,1,1112,5,4,3,2,1}) = " + balanced.swing(new int[]{1,2,3,4,5,1,1112,5,4,3,2,1})); } }
====================================================================