I have 2 lists.
List<Integer> data = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> partitionHelper = Arrays.asList(1, 3, 4, 5);
I want to distribute the data
list into chunks using the partitionHelper
.
For above example the output should be
List<List<Int>> partition = chunk(data, partitionHelper)
//partition = {{1}, {2,3,4}, {5,6,7,8}, {9,10}}
It can be safely assumed that partitionHelper.sum()
>= data.size()
.
I need an O(n + m) algorithm preferably (where n = partitionHelper.size()
and m = data.size())
Any pointers as to how List<List<T>> chunk(List<T>, List<Integer>)
function implementation should look?
PS: I am looking for a functional style approach. Not the standard iterative one.
EDIT:
In Scala I would do something like this
def chunkList(data: List[Int], p: List[Int]): List[List[Int]] = {
def chunk(data: List[Int], p: List[Int], acc: List[List[Int]]): List[List[Int]] =
if (p.nonEmpty && data.nonEmpty) {
chunk(data.drop(p.head), p.tail, acc :+ data.take(p.head))
} else {
acc
}
chunk(data, p, List())
}
> chunkList((1 to 10).toList, List(1,3,4,5))
> res2: List[List[Int]] = List(List(1), List(2, 3, 4), List(5, 6, 7, 8), List(9, 10))
Another Haskell implementation for both foldl and foldr can be found here
> result = new ArrayList<>(partitionHelper.size()); int i = 0; for (int size : partitionHelper) result.add(data.subList(i, Math.min(i += size, data.size())));`
– shmosel Jul 07 '17 at 22:25> chunkList(List data, List p) {
return chunk(data, p, 0);
}
public static List
– Ashwani Jul 08 '17 at 05:56> chunk(List data, List p, int k) {
List
> result = new ArrayList<>(); if (p.get(k) >= data.size()) { result.add(data); } else { result.add(data.subList(0, p.get(k))); result.addAll(chunk(data.subList(p.get(k), data.size()), p, k + 1)); } return result; }`