Working with arrays (flatten, transpose, verfify rectangular)

anonymouse anony at mouse.com
Thu Jul 21 16:23:25 UTC 2022


On Wednesday, 20 July 2022 at 20:47:28 UTC, ag0aep6g wrote:
>
> (Aside: You don't need that many backticks to mark code 
> fragments.)

Thought I was following the instructions but it looks like I got 
a bit carried away. lol.

> You've got a bug there. This should pass, but fails with your 
> version:
>
>     assert(!isRectangular([[1, 2], [], [3, 4]]));
>
> Once `result` becomes false, you cannot let it switch to true 
> again.

Yeah, I noticed that. I actually fixed it at one point but since 
I was having problems scaling whole thing beyond 2D, I thought I 
got it wrong.

> As for generalizing the function, instead of comparing the 
> lengths of the elements, you want to compare their "shapes". 
> The shape of a `Foo[] a1;` is `[a1.length]`. The shape of a 
> rectangular `Foo[][] a2;` is `[a2.length, a2[0].length]`. And 
> so on.
>
[...]

Thank you so much. That was super helpful.

>
> I'm sure the function can be improved further, but I'm not 
> going to get into that.
>
>> For task 3, I can visit each element of the array, but I have 
>> no idea how to compose the flattened (1D) version:
>> 
> You've got the right idea there with `flatten` calling itself 
> on each element. You only need to apply that idea when getting 
> the element type, too (and actually append the result of the 
> recursive call to `result`):
>
>         import std.range.primitives: ElementType;
>         template FlatElementType(A) if (isArray!A)
>         {
>             alias E = ElementType!A;
>             static if (isArray!E)
>             {
>                 alias FlatElementType = FlatElementType!E;
>             }
>             else
>             {
>                 alias FlatElementType = E;
>             }
>         }

This is pure gold. Thank you.

>                     result ~= flatten(i);

Wow. That simple. I actually printed out the contents of result 
and saw the entire thing got was flattened during the recursion, 
but for the life of me I couldn't figure out why the final output 
always be empty.

>
> [...]
>> As for task 3, while I understand the concept of transposing a 
>> matrix, I'm not sure how to even begin.
>
> I'm gonna leave that one for someone else.

Thanks again. I really appreciate the assistance.

--anonymouse


More information about the Digitalmars-d-learn mailing list