Matrix transposition: Difference between revisions

Content added Content deleted
(→‎{{header|Pascal}}: add example)
(Updated both D entries)
Line 646: Line 646:


=={{header|D}}==
=={{header|D}}==
===Locally Procedural Style===
<lang d>import std.stdio, std.algorithm, std.array, std.conv;
<lang d>import std.stdio;


auto transpose(T)(immutable /*in*/ T[][] m) pure nothrow {
T[][] transpose(T)(immutable /*in*/ T[][] m) pure nothrow {
auto r = new T[][](m[0].length, m.length);
auto r = new typeof(return)(m[0].length, m.length);
foreach (nr, row; m)
foreach (nr, row; m)
foreach (nc, c; row)
foreach (nc, c; row)
Line 661: Line 662:
[18, 19, 20, 21]];
[18, 19, 20, 21]];
immutable T = transpose(M);
immutable T = transpose(M);
writeln("[", join(map!text(T), "\n "), "]");
writefln("%(%(%2d %)\n%)", T);
}</lang>
}</lang>
{{out}}
Output:
<pre>[[10, 14, 18]
<pre>10 14 18
[11, 15, 19]
11 15 19
[12, 16, 20]
12 16 20
[13, 17, 21]]</pre>
13 17 21</pre>
Functional style (same output):
===Functional Style===
Same output.
<lang d>import std.stdio, std.algorithm, std.conv, std.range;
<lang d>import std.stdio, std.algorithm, std.range;


auto transpose(T)(in T[][] m) /*pure nothrow*/ {
auto transpose(T)(in T[][] m) /*pure nothrow*/ {
return map!(i => transversal(m, i))(iota(m[0].length));
return iota(m[0].length).map!(i => transversal(m, i))();
}
}


Line 680: Line 682:
[18, 19, 20, 21]];
[18, 19, 20, 21]];
/*immutable*/ auto T = transpose(M);
/*immutable*/ auto T = transpose(M);
writeln("[", join(map!text(T), "\n "), "]");
writefln("%(%(%2d %)\n%)", T);
}</lang>
}</lang>