|
| 1 | +package com.array.rotations; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Comparator; |
| 6 | +import java.util.List; |
| 7 | +import java.util.stream.Collectors; |
| 8 | +import java.util.stream.IntStream; |
| 9 | + |
| 10 | +public class SubArraySample { |
| 11 | + |
| 12 | + // Create in integer array (1,...10) |
| 13 | + // input n = 2 |
| 14 | + // output should be [1,2] [3,4] |
| 15 | + |
| 16 | + |
| 17 | + public static void main(String arg[]) { |
| 18 | + List<Integer> ll = Arrays.asList(1,5,2,3, 5,4,6,1,7, 8,2,9, 3,4); |
| 19 | + int n =5; |
| 20 | + System.out.println( |
| 21 | + IntStream |
| 22 | + .range(0, (ll.size() + n - 1) / n) |
| 23 | + .mapToObj(i -> ll.subList(i * n, Math.min((i + 1) * n, ll.size()))) |
| 24 | + .collect(Collectors.toList())); |
| 25 | + |
| 26 | + List<List<Integer>> result = null;//getSubArray(ll, n); |
| 27 | + //result.forEach(System.out::println); |
| 28 | + } |
| 29 | + |
| 30 | + private static List<List<Integer>> getSubArray(List<Integer> ll, int n) { |
| 31 | + |
| 32 | + List<List<Integer>> result = new ArrayList<>(); |
| 33 | + List<Integer> subArray = new ArrayList<>(); |
| 34 | + for (Integer num : ll) { |
| 35 | + subArray.add(num); |
| 36 | + if(subArray.size() == n) { |
| 37 | + result.add(subArray); |
| 38 | + subArray = new ArrayList<>(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if(!subArray.isEmpty()) { |
| 43 | + result.add(subArray); |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + return IntStream |
| 48 | + .range(0, (ll.size() + n - 1) / n) |
| 49 | + .mapToObj(i -> ll.subList(i * n, Math.min((i + 1) * n, ll.size()))) |
| 50 | + .collect(Collectors.toList()); |
| 51 | + |
| 52 | + //return result; |
| 53 | + } |
| 54 | + |
| 55 | + public static void main1(String arg[]) { |
| 56 | + List<Integer> ll = Arrays.asList(1,5,2,3, 5,4,6,1,7, 8,2,9, 3,4); |
| 57 | + int n =2; |
| 58 | + List<List<Integer>> sequences = subArrayBasedOnIndex(ll, n); |
| 59 | + sequences.forEach(System.out::println); |
| 60 | + |
| 61 | + List<Integer> finalResult = sequences |
| 62 | + .stream() |
| 63 | + .flatMap(list->list.parallelStream()) |
| 64 | + .sorted(Comparator.reverseOrder()) |
| 65 | + .collect(Collectors.toList()); |
| 66 | + |
| 67 | + System.out.println(finalResult); |
| 68 | + } |
| 69 | + |
| 70 | + private static List<List<Integer>> subArrayBasedOnIndex(List<Integer> ll, int n) { |
| 71 | + List<List<Integer>> sequences = new ArrayList<>(); |
| 72 | + List<Integer> subSeq = new ArrayList<>(); |
| 73 | + |
| 74 | + for (int index=0; index < ll.size() ; index++) { |
| 75 | + subSeq.add(ll.get(index)); |
| 76 | + if(subSeq.size() == n) { |
| 77 | + sequences.add(subSeq); |
| 78 | + subSeq = new ArrayList<>(); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + if(!subSeq.isEmpty()) { |
| 83 | + sequences.add(subSeq); |
| 84 | + } |
| 85 | + |
| 86 | + return sequences; |
| 87 | + } |
| 88 | + |
| 89 | +} |
0 commit comments