# Fill an empty matrix with the depth of its elements

Given an arbitrarily nested empty matrix like for example

mat =
{
{},
{{}, {}},
{{}, {{}}, {}},
{{}, {{}}, {}, {{{}}}}
};


and knowing that

Depth /@ mat


{2, 3, 4, 5}

Question 1

how can I produce the following result?

res =
{
{2},
{{3}, {3}},
{{3}, {{4}}, {3}},
{{3}, {{4}}, {3}, {{{5}}}}
};


Question 2

Given

{{2}, {3, 3}, {3, 4, 3}, {3, 4, 3, 5}};


how can I produce the above empty matrix mat ?

• Challenge : How many different ways can we achieve this? challenge-community Nov 13, 2023 at 11:00
• Similar to 26056.
– Syed
Nov 21, 2023 at 4:28

# Q1

res === ReplacePart[
mat,
# -> {1+Length[#]}& /@ Position[mat, {} ]
]
(* True *)


### My MapIndexedattempt

I liked the solutions by @kglr and @lericr, so my version of it (*) is:

res === (
MapIndexed[ {1 + Length[#2]}&, mat, {-2} ]
)
(* True *)


* (In the spirit of the saying that plagiarism is the best form of flattery.)

# Q2

Using Nest, List, Nothing and ReplaceAll (/.)

mat === (
{
{2},
{3, 3},
{3, 4, 3},
{3, 4, 3, 5}
} /. x_Integer :> Nest[List, Nothing, x-2 ]
)
(* True *)

• Nest[List, Nothing, x-2 ] - so simple and yet: Probably I would never have found it
– eldo
Nov 13, 2023 at 11:01

### MapIndexed

MapIndexed[# /. {} -> 1 + {Length @ #2} &, mat, All]

 {{2}, {{3}, {3}}, {{3}, {{4}}, {3}}, {{3}, {{4}}, {3}, {{{5}}}}}


### Position + ReplaceAll

$$i = 0; mat2 = mat /. {} :> {++$$i};

mat2 /. i_Integer :> Length @ First @ Position[mat2, i]

 {{2}, {{3}, {3}}, {{3}, {{4}}, {3}}, {{3}, {{4}}, {3}, {{{5}}}}}


### InternalCopyListStructure + Position

InternalCopyListStructure[mat /. {}->{1}, 1 + Map[Length] @ Position[mat, {}]]

  {{2}, {{3}, {3}}, {{3}, {{4}}, {3}}, {{3}, {{4}}, {3}, {{{5}}}}}


### FixedPoint + ReplaceAll

depths = {{2}, {3, 3}, {3, 4, 3}, {3, 4, 3, 5}};

FixedPoint[ReplaceAll[{0 -> Nothing, i_Integer :> {i - 1}}], depths - 2]

{{}, {{}, {}}, {{}, {{}}, {}}, {{}, {{}}, {}, {{{}}}}}

 % == mat

True


Using ReplaceAll(/.) & Depth

Q1:

res === Map[# /. {} -> Depth@# &, mat /. {} -> {{}}, {2}]
(*True*)


Using ReplaceRepeated

Q2

input = {
{2},
{3, 3},
{3, 4, 3},
{3, 4, 3, 5}
};
mat === Map[
{e} |-> {e} //. {e_?Positive -> List[e - 1], {{{0}}} -> Nothing}, input, {2}]
(*True*)

• AFAICS, the input for Q2 is not res but Flatten/@ res. Nov 13, 2023 at 11:17
• @rhermans Thx, I did not pay enough attention. I deleted the second part. Nov 13, 2023 at 11:22
• No problem, you can still add to it. (+1) Nov 13, 2023 at 11:23

# Q1

1 + MapIndexed[List@*Length@*Last, mat, {-2}]


# Q2

Map[Nest[List, Nothing, # - 2] &, input, {-1}]