JavaScript
class GaussJordan {
constructor(matrix) {
this.matrix = matrix;
this.rows = matrix.length;
}
print() {
for (let i = 0; i < this.rows; i++) {
console.log(this.matrix[i]);
}
console.log("");
}
reduceRow(r1, r2, pos) {
if (r1.length != r2.length) {
return false;
}
let factor = r2[pos] / r1[pos];
for (let i = pos; i < r1.length; i++) {
r2[i] -= factor * r1[i];
}
return true;
}
solve() {
let k; // pivot
let swapTemp;
for (let i = 0; i < this.rows; i++) {
k = i;
for (let j = i + 1; j < this.rows; j++) {
if (this.matrix[j][i] > this.matrix[k][i]) {
k = j;
}
}
if (this.matrix[k][i] == 0) {
console.log("System of equations contains free variables");
return;
}
// Swap the rows i and k
swapTemp = this.matrix[i];
this.matrix[i] = this.matrix[k];
this.matrix[k] = swapTemp;
// Iterate over all subsequent rows
for (let j = 0; j < this.rows; j++) {
// Reduce row by row
if (i != j && !this.reduceRow(this.matrix[i], this.matrix[j], i)) {
console.log("System of equations cannot be solved");
return;
}
}
this.print();
}
}
}
new GaussJordan([
[1, 1, 0, 0, 0, 0, 0, 47],
[0, 1, 1, 0, 0, 0, 0, 39],
[0, 0, 0, 1, 0, 0, 0, 12],
[0, 0, 0, 0, 0, 0, 1, 5],
[-1, 0, 0, 1, 1, 0, 0, 0],
[0, -1, 0, 0, 1, 1, 0, 0],
[0, 0, -1, 0, 0, 1, 1, 0],
]).solve();