I am learning Jjava and I found an interesting exercise on ArrayLists. The purpose is to write a function partition()
which takes a parameter list
and a parameter size
and returns a list of sub-list, where each sub-list has the maximum size
element.
For example:
partition([1,2,3,4,5], 2)
should return[ [1,2], [3,4], [5] ]
,partition([1,2,3,4,5], 3)
should return[ [1,2,3], [4,5] ]
,partition([1,2,3,4,5], 1)
should return[ [1], [2], [3], [4], [5] ]
.
I did this but it works only if the parameter size
is equal to 1
and I want to do it for all cases, and I'm struggling if someone can help me, please.
public static void main(String[] args) {
Apside t = new Apside();
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
System.out.println(t.partition(a, 1));
}
public ArrayList<ArrayList> partition(ArrayList<Integer> l, int n) {
ArrayList<ArrayList> al = new ArrayList();
for (int i = 0; i < n; i++) {
for (int j = 0; j < l.size(); j++) {
for(int k =0; k<n; k++){
ArrayList<Integer> list = new ArrayList(n);
int b = l.get(j);
list.add(b);
al.add(list);
}
}
}
return al;
}