1
|
7154 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
GROUPS:

# Can Insert be modified to insert multiple elements simultaneously?

Posted 11 years ago
 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
Sort By:
Posted 11 years ago
 Modification of pInsert from stackexchange lets you go deeperinsertPart[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 elementinsertPart[origlist, {r, x}, {{1}, {5, 2}}]{r, a, x, b, c, d, x, e, f, g}Multiple insertions at lower levelsinsertPart[{{a, b}, {c, d}}, {xx}, {{{2, 1}, {1, 2}}}]{{a, xx, b}, {xx, c, d}}
Posted 11 years ago