A \'array palindrome\' is an array which, when its elements are reversed, remain
ID: 3817404 • Letter: A
Question
A 'array palindrome' is an array which, when its elements are reversed, remains the same (i.e., the elements of the array are same when scanned forward or backward) Write a recursive, bool-valued function, isPalindrome, that accepts an integer -valued array , and the number of elements and returns whether the array is a palindrome.
The maximum-valued element of an integer -valued array can be recursively calculated as follows:
If the array has a single element , that is its maximum (note that a zero-sized array has no maximum)
Otherwise, compare the first element with the maximum of the rest of the array -- whichever is larger is the maximum value .
Write an int function named max that accepts an integer array , and the number of elements in the array and returns the largest value in the array . Assume the array has at least one element .
Explanation / Answer
MaxTest.java
public class MaxTest {
public static void main(String[] args) {
int a[] = {1,2,3,11,5,6,7,9,8};
System.out.println("Max Value is "+max (a, 5,8));
}
public static int max (int[] a, int start, int last) {
if (start < last) {
return Math.max(a[start], max (a, start+1, last));
} else {
return a[start];
}
}
}
Output:
Max Value is 9
PalindromeArray.java
public class PalindromeArray {
public static void main(String[] args) {
System.out.println(isPalindrome(new int[]{1,2,3,2,1},5));
System.out.println(isPalindrome(new int[]{1,2,4,3,5},5));
}
public static boolean isPalindrome(int a[], int n){
if(n == 0 || n == 1)
return true;
if(a[a.length-n] != a[n-1])
return false;
return isPalindrome(a,n-1);
}
}
Output:
true
false
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.