Create a program that contains a method that does the following; The name of you
ID: 3859520 • Letter: C
Question
Create a program that contains a method that does the following; The name of your method shall be named isBalanced. This method will take a non-empty array of integers and return true if the array can be split in a way that the sum of numbers on the left side equals the sum of numbers in the right side, return false otherwise.
i.e.
isBalanced({2,2,3,3,4}) - true
isBalanced({2,1,3,3,4}) - false
isBalanced({3,1,1,1}) - true
With in your program create an additional method called intGroups that would take an integer as an argument and return the appropriate array. The array would be constructed as follows; given n>= 0, the array shall have the pattern {1, 1, 2, 1, 2, 3, ... 1, 2, 3 .. n} (spaces added to show the grouping). Take into account that the length of the array will be 1 + 2 + 3 ... + n, which is known to sum to exactly n*(n + 1)/2.
i.e.
intGroups(3) - {1,1,2,1,2,3}
intGroups(2) - {1,1,2}
In addition create a method that takes an array of ints and n int, and returns true if the sum of consecutive ints add up to n, false otherwise. Example, given the array {2,7,3,8,4} and n=10, shall return true since 7 + 3=10 and they are consecutive. In the other hand if n=15 than it shall also returns true because of 3+8+4.
All these methods shall be tested in side your main to prove that they work. Do not write the code of these methods inside your main only code that would test your methods thoroughly. For the second problem try to print your array.
Explanation / Answer
UtilityClass.java
public class UtilityClass {
public boolean isBalanced(int arr[])
{
int n=arr.length;
int i, j;
int lsum, rsum;
for (i = 0; i < n; ++i)
{
lsum = 0;
rsum = 0;
for (j = 0; j <=i; j++)
lsum += arr[j];
for (j = i + 1; j < n; j++)
rsum += arr[j];
if (lsum == rsum)
return true;
}
return false;
}
public int[] intGropus(int n)
{
int size=(n*(n+1))/2;
int k=0;
int arr[]=new int[size];
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
arr[k]=j+1;
k=k+1;
}
}
return arr;
}
public boolean isConsecutive(int arr[],int n) {
int sum;
for(int i=0;i<arr.length;i++)
{
sum=0;
for(int j=i;j<arr.length;j++)
{
sum=sum+arr[j];
if(sum==n)
return true;
}
}
return false;
}
}
TestUtilityClass.java
public class TestUtilityClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
UtilityClass utility=new UtilityClass();
int arr[]= {2,2,2,3,3,6};
System.out.println(utility.isBalanced(arr));
int arr1[]=utility.intGropus(5);
System.out.print("{ ");
for(int i : arr1)
{
System.out.print(i+",");
}
System.out.println("}");
int arr2[]= {2,7,3,8,4};
System.out.println(utility.isConsecutive(arr2,15));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.