Search code examples
maple

insert element in every position of nested list


In Maple 15, I have a nested list like this one (only 2 levels of nesting):

[[a,b],[c],[d,e,f]]

I want to create 6 lists from that one (the number of elements..), like these:

[[x,a,b],[c],[d,e,f]]
[[a,x,b],[c],[d,e,f]]
[[a,b],[x,c],[d,e,f]]
[[a,b],[c],[x,d,e,f]]
[[a,b],[c],[d,x,e,f]]
[[a,b],[c],[d,e,x,f]]

I tried but I have super complex loops and it doesn't work.. any more brilliant idea?


Solution

  • I am writing this code on Maple 7, but it should work with pretty much any version of Maple. I feel that it is easier to do things by first stripping the original nested list into two simple lists:

    input:=[[a,b],[c],[d,e,f]];
    flatlist:=[seq(op(input[n]),n=1..nops(input))]; % flat list of all elements
    noels:=[seq(nops(input[n]),n=1..nops(input))]; % numbers of elements in sub-lists
    

    It is easier to insert your extra elements into the new flat lists:

    newlists:=[seq([seq(flatlist[i],i=1..n-1),x,seq(flatlist[i],i=n..nops(flatlist))],n=1..nops(flatlist))];
    newnoels:=[seq(seq([seq(noels[i],i=1..n-1),noels[n]+1,seq(noels[i],i=n+1..nops(noels))],m=1..noels[n]),n=1..nops(noels))];
    

    The resulting flat lists must be converted back into the nested lists. This can be done by writing a simple function:

    mergelists:=proc(flatlist,noels)
      local i,j,n,result;
      i:=0; result:=NULL;
      for n from 1 to nops(noels) do
        result:=result,[seq(flatlist[i+j],j=1..noels[n])];
        i:=i+noels[n];
      od;
      return [result];
    end:
    

    With this function available, it is now easy to convert the prepared data into the required format:

    output:=[seq(mergelists(newlists[n],newnoels[n]),n=1..nops(newlists))];
    

    I admit that this may not be the most elegant solution possible. Unfortunately, nothing simpler comes to my mind just now.