Display a linear combination: Difference between revisions

Added D
(Added D)
Line 132:
Vector for [-1] -> - e1
</pre>
 
=={{header|D}}==
{{trans|Kotlin}}
<lang D>import std.array;
import std.conv;
import std.format;
import std.math;
import std.stdio;
 
string linearCombo(int[] c) {
auto sb = appender!string;
foreach (i, n; c) {
if (n==0) continue;
string op;
if (n < 0) {
if (sb.data.empty) {
op = "-";
} else {
op = " - ";
}
} else if (n > 0) {
if (!sb.data.empty) {
op = " + ";
}
}
auto av = abs(n);
string coeff;
if (av != 1) {
coeff = to!string(av) ~ "*";
}
sb.formattedWrite("%s%se(%d)", op, coeff, i+1);
}
if (sb.data.empty) {
return "0";
}
return sb.data;
}
 
void main() {
auto combos = [
[1, 2, 3],
[0, 1, 2, 3],
[1, 0, 3, 4],
[1, 2, 0],
[0, 0, 0],
[0],
[1, 1, 1],
[-1, -1, -1],
[-1, -2, 0, -3],
[-1],
];
foreach (c; combos) {
auto arr = c.format!"%s";
writefln("%-15s -> %s", arr, linearCombo(c));
}
}</lang>
{{out}}
<pre>[1, 2, 3] -> e(1) + 2*e(2) + 3*e(3)
[0, 1, 2, 3] -> e(2) + 2*e(3) + 3*e(4)
[1, 0, 3, 4] -> e(1) + 3*e(3) + 4*e(4)
[1, 2, 0] -> e(1) + 2*e(2)
[0, 0, 0] -> 0
[0] -> 0
[1, 1, 1] -> e(1) + e(2) + e(3)
[-1, -1, -1] -> -e(1) - e(2) - e(3)
[-1, -2, 0, -3] -> -e(1) - 2*e(2) - 3*e(4)
[-1] -> -e(1)</pre>
 
=={{header|EchoLisp}}==
1,452

edits