Reduced row echelon form: Difference between revisions

Content added Content deleted
(→‎{{header|Euphoria}}: Euphoria example added)
(Shorter D code)
Line 700: Line 700:


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


pure nothrow bool isRectangular(T)(in T[][] M) {
void toReducedRowEchelonForm(T)(T[][] M) pure {
foreach (row; M)
const nrows = M.length;
if (row.length != M[0].length)
if (!nrows) return;
return false;
const ncols = M[0].length;
return true;
int lead;
foreach (r; 0 .. nrows) {
}
if (ncols <= lead) return;

pure void toReducedRowEchelonForm(T)(T[][] M)
in {
assert(isRectangular(M));
}
body {
if (!M.length)
return;
immutable int rowCount = M.length;
immutable int columnCount = M[0].length;
int lead = 0;
foreach (r; 0 .. rowCount) {
if (columnCount <= lead)
return;
int i = r;
int i = r;
while (M[i][lead] == 0) {
while (M[i][lead] == 0)
i++;
if (nrows == ++i) {
if (rowCount == i) {
i = r;
i = r;
lead++;
if (ncols == ++lead) return;
if (columnCount == lead)
return;
}
}
}
swap(M[i], M[r]);
swap(M[i], M[r]);
M[r][] /= M[r][lead];
M[r][] /= M[r][lead];
foreach (j; 0 .. rowCount)
foreach (j; 0 .. nrows)
if (j != r)
if (j != r)
M[j][] -= M[r][] * M[j][lead];
M[j][] -= M[r][] * M[j][lead];
Line 742: Line 725:


void main() {
void main() {
auto mtx = [[ 1, 2, -1, -4],
auto A = [[ 1, 2, -1, -4],
[ 2, 3, -1, -11],
[ 2, 3, -1, -11],
[-2, 0, -3, 22]];
[-2, 0, -3, 22]];
toReducedRowEchelonForm(mtx);
toReducedRowEchelonForm(A);
writeln("[", array(map!text(A)).join("\n "), "]");
foreach (row; mtx)
writeln(row);
}</lang>
}</lang>
Output:
Output:
<pre>[1, 0, 0, -8]
<pre>[[1, 0, 0, -8]
[0, 1, 0, 1]
[0, 1, 0, 1]
[0, 0, 1, -2]</pre>
[0, 0, 1, -2]]</pre>


=={{header|Euphoria}}==
=={{header|Euphoria}}==