2
$\begingroup$

I have an initial "multidimensional" list (that is, a list that is not a vector):

list0 = {{1},{2,3,4},{3,4},{5}};

and I want to insert elements x,y,z at specific positions {1,1}, {2,3}, {4,2}, to obtain the resulting list:

{{x,1},{2,3,y,4},{3,4},{5,z}}

That is, the list of positions {1,1}, {2,3}, {4,2} gives the positions in the resulting list.

What's a clean way to do this?

This is a generalization of Insert at specific resulting positions?, which is a one-dimensional version of this question.

$\endgroup$
  • $\begingroup$ @Kuba Typo. Fixed. $\endgroup$ – becko Dec 4 '14 at 18:19
  • $\begingroup$ What when positions are {2,2} and {2,3} for example, should it behave like Insert so: ... {2, x, 3, y, 4}... or rather {2, x, y, 3, 4}? Where the latter is maybe intuitive but not consistent with Insert. $\endgroup$ – Kuba Dec 4 '14 at 18:30
2
$\begingroup$

The function insertF in the answer to your linked question also works for the multidimensional case:

insertF = Fold[Insert[#, #2[[1]], #2[[2]]] &, #,  SortBy[Transpose[{#2, #3}], Last]] &;

list0 = {{1},{2,3,4},{3,4},{5}};
parts = {{1, 1}, {2, 3}, {4, 2}};
insertF[list0, {x, y, z}, parts]
(* {{x, 1}, {2, 3, y, 4}, {3, 4}, {5, z}} *)

list0 = {{1},{2,3,4},{3,4},{5}};    
parts2 = {{1, 1}, {2, 3}, {4, 2}};
insertF[list0, {x, y,  z}, parts2]
(* {{1}, {2,x,y,3,4}, {3,4}, {5,z}} *)
$\endgroup$
3
$\begingroup$
inserttt[where_, what_, whereExactly_] := (
    # = 0;
    Insert[where, Unevaluated[what[[++#]]], whereExactly]
    ) & @ Unique["whatever"]

 inserttt[{{1}, {2, 3, 4}, {3, 4}, {5}}, 
          {x, y, z},
          {{2, 2}, {2, 3}, {4, 2}}]
 {{1}, {2, x, 3, y, 4}, {3, 4}, {5, z}}

old, incorrect, failing with {{2,2}, {2,3}.. cases:

I find your description not consistent with code samples, but here is what I've understood:

inserttt[where_, what_, whereExactly_] := ReplacePart[
                                           Insert[where, "", whereExactly],
                                           Thread[whereExactly -> what]
                                           ]


inserttt[{{1}, {2, 3, 4}, {3, 4}, {5}}, 
         {x, y, z}, 
         {{1, 1}, {2, 3}, {4, 2}}]
{{x, 1}, {2, 3, y, 4}, {3, 4}, {5, z}}
$\endgroup$
  • $\begingroup$ That doesn't work as I want. The position of y in {{1}, {2, x, 3, y, 4}, {3, 4}, {5, z}} is {2,4}, but I want it to be {2,3}. The output I expect from inserttt[{{1}, {2, 3, 4}, {3, 4}, {5}}, {x, y, z}, {{2, 2}, {2, 3}, {4, 2}}] is {{1},{2,x,y,3,4},{3,4},{5,z}} $\endgroup$ – becko Dec 4 '14 at 18:48
  • $\begingroup$ @becko I understand. I will try to fix it later. Now it is at least consistent with Insert. $\endgroup$ – Kuba Dec 4 '14 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.