2

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.

a06e
  • 11,327
  • 4
  • 48
  • 108
  • @Kuba Typo. Fixed. – a06e Dec 04 '14 at 18:19
  • 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. – Kuba Dec 04 '14 at 18:30

2 Answers2

3
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}}
Kuba
  • 136,707
  • 13
  • 279
  • 740
  • 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}} – a06e Dec 04 '14 at 18:48
  • @becko I understand. I will try to fix it later. Now it is at least consistent with Insert. – Kuba Dec 04 '14 at 19:08
2

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}} *)
kglr
  • 394,356
  • 18
  • 477
  • 896