RosettaCodeData/Task/Matrix-arithmetic/D/matrix-arithmetic.d

56 lines
1.7 KiB
D
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import std.algorithm, std.range, std.traits, permutations2,
permutations_by_swapping1;
2015-02-20 00:35:01 -05:00
auto prod(Range)(Range r) nothrow @safe @nogc {
return reduce!q{a * b}(ForeachType!Range(1), r);
2013-04-10 21:29:02 -07:00
}
2015-02-20 00:35:01 -05:00
T permanent(T)(in T[][] a) nothrow @safe
2013-04-10 21:29:02 -07:00
in {
2015-02-20 00:35:01 -05:00
assert(a.all!(row => row.length == a[0].length));
2013-04-10 21:29:02 -07:00
} body {
2013-10-27 22:24:23 +00:00
auto r = a.length.iota;
2013-04-10 21:29:02 -07:00
T tot = 0;
2015-02-20 00:35:01 -05:00
foreach (const sigma; r.array.permutations)
2013-10-27 22:24:23 +00:00
tot += r.map!(i => a[i][sigma[i]]).prod;
2013-04-10 21:29:02 -07:00
return tot;
}
2015-02-20 00:35:01 -05:00
T determinant(T)(in T[][] a) nothrow
2013-04-10 21:29:02 -07:00
in {
2015-02-20 00:35:01 -05:00
assert(a.all!(row => row.length == a[0].length));
2013-04-10 21:29:02 -07:00
} body {
immutable n = a.length;
2013-10-27 22:24:23 +00:00
auto r = n.iota;
2013-04-10 21:29:02 -07:00
T tot = 0;
2013-10-27 22:24:23 +00:00
//foreach (sigma, sign; n.spermutations) {
2015-02-20 00:35:01 -05:00
foreach (const sigma_sign; n.spermutations) {
2013-04-10 21:29:02 -07:00
const sigma = sigma_sign[0];
immutable sign = sigma_sign[1];
2013-10-27 22:24:23 +00:00
tot += sign * r.map!(i => a[i][sigma[i]]).prod;
2013-04-10 21:29:02 -07:00
}
return tot;
}
void main() {
import std.stdio;
2013-10-27 22:24:23 +00:00
foreach (/*immutable*/ const a; [[[1, 2],
[3, 4]],
2013-04-10 21:29:02 -07:00
2013-10-27 22:24:23 +00:00
[[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10],
[10, 11, 12, 13]],
2013-04-10 21:29:02 -07:00
2013-10-27 22:24:23 +00:00
[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]]]) {
2013-04-10 21:29:02 -07:00
writefln("[%([%(%2s, %)],\n %)]]", a);
writefln("Permanent: %s, determinant: %s\n",
2013-10-27 22:24:23 +00:00
a.permanent, a.determinant);
2013-04-10 21:29:02 -07:00
}
}