|
| 1 | +package easy; |
| 2 | + |
| 3 | +/** |
| 4 | + * Have the function ArithGeo(arr) take the array of numbers stored in arr |
| 5 | + * and return the string "Arithmetic" if the sequence follows an arithmetic pattern |
| 6 | + * or return "Geometric" if it follows a geometric pattern. |
| 7 | + * --- |
| 8 | + * If the sequence doesn't follow either pattern return -1. |
| 9 | + * An arithmetic sequence is one where the difference between |
| 10 | + * each of the numbers is consistent, where in a geometric sequence, |
| 11 | + * each term after the first is multiplied by some constant or common ratio. |
| 12 | + * --- |
| 13 | + * Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. |
| 14 | + * Negative numbers may be entered as parameters, 0 will not be entered, |
| 15 | + * and no array will contain all the same elements. |
| 16 | + */ |
| 17 | +public class ArithGeo { |
| 18 | + |
| 19 | + /** |
| 20 | + * Arith Geo function. |
| 21 | + * |
| 22 | + * @param arr input array of integers |
| 23 | + * @return the string "Arithmetic" if the sequence follows an arithmetic pattern |
| 24 | + */ |
| 25 | + private static String arithGeo(int[] arr) { |
| 26 | + |
| 27 | + int arithInterval = arr[1] - arr[0]; |
| 28 | + int geoInterval = arr[1] / arr[0]; |
| 29 | + int arithCount = 0; |
| 30 | + int geoCount = 0; |
| 31 | + |
| 32 | + for (int i = 0; i < arr.length - 1; i++) { |
| 33 | + if (arr[i + 1] - arr[i] == arithInterval) { |
| 34 | + arithCount++; |
| 35 | + } |
| 36 | + if (arr[i + 1] / arr[i] == geoInterval) { |
| 37 | + geoCount++; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + if (arithCount == arr.length - 1) { |
| 42 | + return "Arithmetic"; |
| 43 | + } |
| 44 | + |
| 45 | + if (geoCount == arr.length - 1) { |
| 46 | + return "Geometric"; |
| 47 | + } |
| 48 | + |
| 49 | + return "-1"; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Entry point. |
| 54 | + * |
| 55 | + * @param args command line arguments |
| 56 | + */ |
| 57 | + public static void main(String[] args) { |
| 58 | + var result1 = arithGeo(new int[]{2, 4, 6, 8}); |
| 59 | + System.out.println(result1); |
| 60 | + var result2 = arithGeo(new int[]{2, 6, 18, 54}); |
| 61 | + System.out.println(result2); |
| 62 | + var result3 = arithGeo(new int[]{-3, -4, -5, -6, -7}); |
| 63 | + System.out.println(result3); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments