Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split long list into pieces in Qore

Tags:

arrays

qore

I'd like to split a list in Qore like this:

list a = (1,2,3,4,5,6);
list pieces = split_list_into_pieces(a, 2);
printf("%y\n", pieces);

Desired output:

[[1,2], [3,4], [5,6]]

I.e. I want to take a (supposedly long) list and split it into pieces of given (max) length.

I can do it like:

list sub split_list_into_pieces(list a, int length)
{
    int i = 0;
    list ret = ();
    list temp = ();
    foreach any x in (a)
    {
        temp += x;
        i++;
        if (i == length)
        {
            push ret, temp;
            temp = ();
            i = 0;
        }
    }
    if (temp)
    {
        push ret, temp;
    }
    return ret;
}

But it is not very elegant, is it?

Any better solution?

like image 577
Pavel Kveton Avatar asked Feb 09 '17 11:02

Pavel Kveton


1 Answers

you can do it this way:

list sub list_chunk(list a, int length) {
    list result = ();
    while (a)
        push (result, extract (a, 0, length));
    return result;
}
like image 112
Martin Zemek Avatar answered Dec 01 '22 05:12

Martin Zemek