Hi all,
I know how to use Java collections but at beginner's level.
I have the list:
[10, 20, 30, 12, 13, 8, 1, 2, 3]
With the following methods:
1) List<List<Integer>> getSubSequences( Iterator<Integer> it, Comparator<Integer> cmp )
2) List<List<Integer>> getSubSequencesAscendentOrder( Iterator<Integer> it )
The outputs must be:
1) [[10, 20, 30], [12, 13], [8], [1, 2, 3]]
and
2) [[1, 2, 3], [8], [10, 20, 30], [12, 13]]
I've implemented the first method and allready works as follows:
class MyComparator implements Comparator<Integer> { public int compare(Integer i1, Integer i2) { return i1 - i2; } } public static List<List<Integer>> getSubSequences(Iterator<Integer> it, Comparator<Integer> cmp) { List<List<Integer>> list = new ArrayList<List<Integer>>(); ArrayList<Integer> subList = new ArrayList<Integer>(); int aux1 = 0; if(it.hasNext()) { aux1 = it.next(); subList.add(aux1); } while(it.hasNext()) { int aux2 = it.next(); if(cmp.compare(aux2, aux1) < 0 ) { list.add(subList); subList = new ArrayList<Integer>(); } subList.add(aux2); aux1 = aux2; } list.add(subLista); return list; }
In public static main() I have:
int array[] = {10, 20, 30, 12, 13, 8, 1, 2, 3}; ArrayList<Integer> li = new ArrayList<Integer>(array.length); for(int i = 0; i < array.length; i++) li.add(array[i]); Iterator<Integer> it = li.iterator(); Comparator cmp = new MyComparator(); List<List<Integer>> res = getSubSequences(it, cmp) ; it = ((List)res).iterator(); while(it.hasNext()) System.out.print(it.next() + " "); System.out.println();
This works fine and the output is [10, 20, 30] [12, 13] [8] [1, 2, 3]
Not exactly [[10, 20, 30], [12, 13], [8], [1, 2, 3]] but close.
I think the method 2) must be very similar to method 1), however I can't implement that.
Can someone give some clues?
Thank you in advance
Paulo