please add comments to explain your code ... thank you ! 3) Create a Test.java c
ID: 3916629 • Letter: P
Question
please add comments to explain your code ... thank you !
3) Create a Test.java class that will include the following static class methods: 2/3 t): A recursive method that finds the sum of all odd values a) public static int sumOdd(int stored in an array of int. b) public static int lastOccureance(int[] t, int n): A recursive linear search method that will find the last occurrence of an int n in an array of integers t. c) public static int [ sumArray(int [ t, int value): a method that will take an array t (e.g., (5,6,7,83) and a desired sum value (e.g., 15), then returns a subset of numbers (c.g. 17,8)), in the array that will result in that sum if such an array exists. If multiple arrays can be found, any one can be returned. For example,if t -(1,1,5,4,6) and value 10, one possible outcome is (1,5,4), another is 4,63 d) Test all the above methods in the main method of your class Test,java Deliverable: Test.iavaExplanation / Answer
package chegg_1;
import java.util.Arrays;
public class Test {
public static int sumOdd(int[] t) {
if (t.length == 1) { //Base Case
if (t[0] % 2 != 0) {
return t[0];
} else {
return 0;
}
}
int sum = sumOdd(Arrays.copyOfRange(t, 1, t.length)); // Recursive Call
if (t[0] % 2 != 0) {
sum += t[0]; //Adding in existing sum drom recursion
}
return sum;
}
public static int lastOccurence(int[] t, int n) {
if (t.length == 1) { //Base Case
int count;
if (t[0] == n) {
count = 0;
} else {
count = -1; //If it has never occurred return -1
}
return count;
}
int lastCount = lastOccurence(Arrays.copyOfRange(t, 1, t.length), n); // recursive Call to collect pointer
if (lastCount == -1) {
if (t[0] == n) { //checking the case for the rest of the array
return 0;
} else {
return -1;
}
} else {
return lastCount + 1; //If already found increasing the pointer by one
}
}
public static int[] sumArray(int[] t, int value) {
if(t.length==1){ //Base Case
if(value==t[0]){
int[] arr = {t[0]};
return arr;
}
else{
return null;
}
}
int[] arr1 = sumArray(Arrays.copyOfRange(t, 1, t.length),value-t[0]); //2 cases : one taking the number
int[] arr2 = sumArray(Arrays.copyOfRange(t, 1, t.length),value); // Another not taking the number
if(arr1!=null){ //returning anyone arr if not null
int[] arrFinal = new int[arr1.length+1];
arrFinal[0] = t[0];
for(int i =1;i<arr1.length+1;i++){
arrFinal[i]= arr1[i-1];
}
}
else if(arr2!=null){
return arr2;
}
return null;
}
//Tried and tested in main
//All the best, for any doubt or error comment and i will try my best to resolve
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.