Advertisement
apad464

MountainRunner.java (2014 FRQ part 2)

Mar 2nd, 2023 (edited)
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. class Mountain {
  4.     public static boolean isIncreasing(int[] array, int stop) {
  5.         for (int i = 0; i < stop; i++)
  6.             if (array[i] > array[i + 1])
  7.                 return false;
  8.         return true;
  9.     }
  10.  
  11.     public static boolean isDecreasing(int[] array, int start) {
  12.         for (int j = start; j<array.length - 1; j++)
  13.             if (array[j] < array[j+1])
  14.                 return false;
  15.         return true;
  16.     }
  17.  
  18.     public static int getPeakIndex(int[] array) {
  19.         for (int i = 1; i < array.length - 1; i++)
  20.             if (array[i] > array[i - 1] && array[i] > array[i + 1])
  21.                 return i;
  22.         return -1;
  23.     }
  24.  
  25.     public static boolean isMountain(int[] array) {
  26.         int index = getPeakIndex(array);
  27.         return index != -1 && isIncreasing(array, index - 1) && isDecreasing(array, index + 1);
  28.     }
  29. }
  30.  
  31. public class MountainRunner {
  32.     public static void main(String[] args) {
  33.         String output = "";
  34.         int[][] arr = {{1, 2, 3, 2, 1}, {1, 2, 1, 2, 1}, {1, 2, 3, 1, 5}, {1, 4, 2, 1, 0}, {9, 3, 5, 7, 5}, {3, 2, 1}};
  35.  
  36.  
  37.  
  38.         for (int[] a : arr)
  39.             System.out.println((Mountain.getPeakIndex(a) != -1 ? "Peak is " + Mountain.getPeakIndex(a) + " - " : "No peak - ")
  40.                     + Arrays.toString(a) + " is a mountain :: " + Mountain.isMountain(a));
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement