Advertisement
Guest User

1.2 (1)

a guest
Sep 16th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. public class Main {
  2.     public static void main(String[] args) {
  3.  
  4.         List<List<Integer>> testSequences = new ArrayList<>();
  5.        
  6.         testSequences.add(Arrays.asList(10, 2, 3, 5, 2, 3, 3, 5, 6, 7));
  7.         testSequences.add(Arrays.asList(10, 9, 8));
  8.         testSequences.add(Arrays.asList(2, 3, 4, 5, 5));
  9.  
  10.         for (List<Integer> sequence : testSequences) {
  11.             List<Integer> longest = findLongestSequence(sequence, (previous, current) -> previous < current);
  12.  
  13.             System.out.println("For sequence " + sequence + " longest is : " + longest + " (length " + longest.size()
  14.                     + ")");
  15.         }
  16.     }
  17.  
  18.     private static List<Integer> findLongestSequence(List<Integer> source, BiPredicate<Integer, Integer> predicate) {
  19.         List<Integer> longestSequence = Collections.emptyList();
  20.  
  21.         int fromIndex = -1;
  22.         int toIndex = -1;
  23.  
  24.         int currentFrom = -1;
  25.         int currentTo;
  26.  
  27.         for (int i = 1; i < source.size(); i++) {
  28.             if (predicate.test(source.get(i - 1), source.get(i))) {
  29.                 if (currentFrom == -1)
  30.                     currentFrom = i - 1;
  31.  
  32.                 if (i == source.size() - 1) {
  33.                     currentTo = source.size();
  34.  
  35.                     if (currentTo - currentFrom > toIndex - fromIndex) {
  36.                         fromIndex = currentFrom;
  37.                         toIndex = currentTo;
  38.                     }
  39.                 }
  40.             } else {
  41.                 currentTo = i;
  42.  
  43.                 if (currentTo - currentFrom > toIndex - fromIndex) {
  44.                     fromIndex = currentFrom;
  45.                     toIndex = currentTo;
  46.                 }
  47.                 currentFrom = -1;
  48.             }
  49.         }
  50.  
  51.         if (fromIndex > -1)
  52.             longestSequence = source.subList(fromIndex, toIndex);
  53.  
  54.         return longestSequence;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement