In: Computer Science
public class Lab1 {
public static void main(String[] args) {
int array [] = {10, 20, 31, 40, 55, 60, 65525};
System.out.println(findPattern(array));
}
private static int findPattern(int[] arr) {
for (int i = 0; i < arr.length - 2; i++) {
int sum = 0;
for (int j = i; j < i + 2; j++) {
sum += Math.abs(arr[j] - arr[j + 1]);
}
if (sum == 20)
return i;
}
return -1;
}
}
QUESTION: Modify the given code such that the input array may wrap-around or over- flow.
Given the input array: data[] = {65515,65525,9,20,31,40,55} The function shall return: 0
public class Lab1 {
public static void main(String[] args) {
int array[] = { 65515,65525,9,20,31,40,55 };
System.out.println(findPattern(array));
}
private static int findPattern(int[] arr) {
//modify the loop to run until
last element of the array
for (int i = 0; i < arr.length;
i++) {
int sum =
0;
//calculate the
sum of difference between consecutive elements
sum =
sum+Math.abs(arr[i]-arr[(i+1)%arr.length]);
sum =
sum+Math.abs(arr[(i+1)%arr.length]-arr[(i+2)%arr.length]);
if (sum ==
20)
return i;
}
return -1;
}
}