daily pastebin goal
72%
SHARE
TWEET

alternating_sequence_caleb_lawrence

a guest Jan 16th, 2018 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class longestAlternating {
  2.     public static void calculateLongestAlternating(int arr[]) {
  3.         int n = arr.length;
  4.  
  5.         // loop through elemnts in array
  6.         for (int i=0; i < n; i++) {
  7.  
  8.             int numberOfAlternating = 1;
  9.  
  10.             // loop through elements in sub array
  11.             for (int j = i; j < n-1; j++) {
  12.                 int multiple = arr[j] * arr[j + 1];
  13.                 // check if multiple is negative
  14.                 if (multiple < 0) {
  15.                     numberOfAlternating = numberOfAlternating + 1;
  16.                 } else {
  17.                     break;
  18.                 }
  19.             }
  20.             System.out.print("For index: " + i + " {");
  21.             for (int k = i; k < arr.length; k++) {
  22.                 if (k > 0) {
  23.                     System.out.print(" ");
  24.                 }
  25.                 System.out.print(arr[k]);
  26.             }
  27.             System.out.println("} = " + numberOfAlternating);
  28.  
  29.         }
  30.  
  31.     }
  32.  
  33.     public static void main(String[] args) {
  34.        // int array[] = {1, -5, 1, -5};
  35. //        int array[] = {-5, -1, -1, 2, -2, -3};
  36.         int array[] = {1, -5, 1, -5};
  37.         calculateLongestAlternating(array);
  38.  
  39.     }
  40.  
  41. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top