Rotate array in writefln?

Chris Katko ckatko at gmail.com
Thu Apr 19 10:10:41 UTC 2018


On Wednesday, 18 April 2018 at 07:15:47 UTC, Simen Kjærås wrote:
> On Wednesday, 18 April 2018 at 06:54:29 UTC, Chris Katko wrote:
>> I need to rotate an array by 90 degrees, or have writefln 
>> figure that out.
>>
>> I need, say:
>>
>> 0 4 5 6
>> 0 0 0 0
>> 0 0 0 0
>> 0 0 0 0
>>
>> But it's outputting:
>>
>> 0 0 0 0
>> 4 0 0 0
>> 5 0 0 0
>> 6 0 0 0
>>
>> int [4][4] data;
>> file.writeln(format("%(%-(%d %)\n%)", data));
>
> Generally, the solution would be std.range.transposed. However, 
> since you're using a int[4][4], that's not a range-of-ranges, 
> and transposed don't work out of the box. This helper function 
> should help:
>
> T[][] ror(T, size_t N1, size_t N2)(ref T[N1][N2] arr)
> {
>     T[][] result = new T[][N2];
>     foreach (i, e; arr) {
>         result[i] = e.dup;
>     }
>     return result;
> }
>
> unittest
> {
>     import std.stdio;
>     import std.range;
>
>     int [4][4] data;
>     data[2][3] = 4;
>     writefln("%(%-(%d %)\n%)", data);
>     writefln("%(%-(%d %)\n%)", data.ror.transposed);
> }
>
> --
>   Simen

That makes sense why transpose wouldn't work for my arrays!

So you're saying if I used [][] (dynamic array) that's a range of 
ranges, and it would work?

Why is it you have to rework your templates for static vs dynamic 
ranges? Thanks!


More information about the Digitalmars-d-learn mailing list