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]); // finding the difference
}
if (sum == 20)
return i;
}
return -1;
}
}
QUESTION: Modify the code segment to generalize the gap spacing. Instead of hard- coding the difference of 20 into the function, change the function signature to include it as a parameter.
public class Lab1 { public static void main(String[] args) { int array[] = {10, 20, 31, 40, 55, 60, 65525}; System.out.println(findPattern(array, 20)); } private static int findPattern(int[] arr, int gap) { 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]); // finding the difference } if (sum == gap) return i; } return -1; } }
Get Answers For Free
Most questions answered within 1 hours.