Message Boards Message Boards

GROUPS:

Can Insert be modified to insert multiple elements simultaneously?

Posted 6 years ago
3445 Views
|
2 Replies
|
2 Total Likes
|
I would like to take the following data:


insertvalues = {r, x};
insertpositions = {{1}, {5}};
origlist = {a, b, c, d, e, f, g};


and generate output that looks like this:

{r,a,b,c,d,x,e,f,g}

Mathematica's Insert command seems limited in that it does not allow you to insert multiple elements simultaneously into different positions in a list.

I wrote an ugly While loop to accomplish this, and it works, but seems inappropriate for Mathematica's functional approach to coding. Is there a "simpler" way to accomplish this goal with a functional approach? Thank you.
 insertvalues = {r, x};
 insertpositions = {{1}, {5}};
 origlist = {a, b, c, d, e, f, g};
 
 loopcounter = 0; poscounter = 0; final = origlist;
 While[loopcounter < Length[insertvalues],
   final =
    Insert[final,
     insertvalues[[loopcounter +
       1]], (insertpositions[[loopcounter + 1]] + poscounter)];
  loopcounter++; poscounter++];
2 Replies
Modification of pInsert from stackexchange lets you go deeper
insertPart[origList_, repList_, posList_] :=
Module[{replaceRules},
replaceRules =Thread[Rule[#[[1]],Sequence[#[[2]], Part[origList, Sequence @@ (#[[1]])]]] & /@
Join @@ (Thread /@ Transpose[{posList, repList}])];
ReplacePart[origList, replaceRules]]
insertPart[origlist, {r, x}, {{1}, {5}}]
{r, a, b, c, d, x, e, f, g}

Multiple insertions for the same element
insertPart[origlist, {r, x}, {{1}, {5, 2}}]
{r, a, x, b, c, d, x, e, f, g}

Multiple insertions at lower levels
insertPart[{{a, b}, {c, d}}, {xx}, {{{2, 1}, {1, 2}}}]
{{a, xx, b}, {xx, c, d}}
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract