Basically I have university work about recursion but I'm having problems solving this. I have to create two methods, one called getLastElement and isSymmetric. getLastElement can only access index 0 from the array. isSymmetric must print true if the array is symmetric or if it's 0. It must use array[0] and array.length. It can also use Arrays.copyOfRange()
I already made isSymmetric but without getLastElement and I think I'm missing something since I don't know how to incorporate getLastElement into it. I know I didn't use array[0] but I couldn't get the code working with it.
Here's my code:
public static int isSymmetric(int array[], int begin, int end)
{
if (begin >= end) {
return 1;
}
if (array[begin] == array[end]) {
return isSymmetric(array, begin + 1, end - 1);
}
else {
return 0;
}
}
public static void main (String[] args) {
int array[] = { 1, 2, 3, 2, 1 };
if (isSymmetric(array, 0, array.length - 1) == 1)
System.out.print( "true");
else
System.out.println( "false");
}
I just want to print just like I am right now but with getLastElement incorporated into isSymmetric.
Instead of sending the whole array along with the indices begin
and end
, you can just use a copy of the array between these two indices. Doing this will allow you to use your getLastElement
function (see code).
// I am assuming this function returns the
// 0th-indexed element of the array.
public static int getLastElement(int[] array) {
return array[0];
}
public static int isSymmetric(int[] array) {
if(array.length <= 1) return 1;
// check if the first and the last element are equal
if(getLastElement(array) == array[array.length -1])
// copy the remaining array (leaving first and last element)
return isSymmetric(Arrays.copyOfRange(array, 1, array.length-1));
return 0;
}
public static void main (String[] args) {
int array[] = { 1, 2, 3, 2, 1 };
if (isSymmetric(array) == 1)
System.out.println( "true");
else
System.out.println( "false");
}
getLastElement
is actually returning the first element of the array, so if you see it is actually a getFristElement
kind of function. This was done because the question states that this function is only allowed to access the 0th-index of the array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.