Question

I am newbie to erlang, I tried a lot myself but could not split the list to N parts.

Here is my list of lists:

L =[ 
    [1, 2, 3, 4, 5], %% Assume L1
    [1, 8, 5, 0, 6], %% Assume L2
    [1, 5, 4, 2, 6], %% Assume L3
    [1, 1, 2, 2, 6], %% Assume L4
    [1, 3, 4, 0, 5], %% Assume L5
    [1, 8, 5, 0, 6], %% Assume L6
    [4, 5, 4, 2, 6], %% Assume L7
    [2, 1, 4, 2, 6], %% Assume L8
    [2, 3, 4, 2, 6]  %% Assume L9
    ...
    [2, 6, 4, 2, 6]  %% Assume Ln
].

and wants to divide it into N parts like:

L = [[L1, L2, L3], [L4, L5, L6], [L7, L8, L9],.... [Ln-1, Ln]]

lists:split() is retrieves only one element. Where, [Ln-1, Ln] would be only two elements in the last part.

Was it helpful?

Solution

I came with something like this:

-module(test).
-compile(export_all).

split([], _) -> [];
split(L, N) when length(L) < N -> [L];
split(L, N) ->
    {A, B} = lists:split(N, L),
    [A | split(B, N)].

It does not merge elements of grouped lists but if needed you can simply do it with lists:merge

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top