function main(vectorsAmount = 10, length = 5, bound = 10) { const startingVectors = randomMatrix(vectorsAmount, length, bound); console.log("Starting vectors:"); print(startingVectors); console.log(); const result = []; for (let i = 0; i < startingVectors.length; i ++) { addIfIndependent(result, startingVectors[i]); } console.log("Ending vectors (" + result.length + "):"); print(result); } function addIfIndependent(independentVectors, testVector) { if (isVectorZero(testVector)) { return; } const matrixCopy = structuredClone(independentVectors); const vectorCopy = structuredClone(testVector); matrixCopy.push(vectorCopy); if (gaussianElimination(matrixCopy)) { independentVectors.push(testVector); } } function isVectorZero(vector) { return vector.every(entry => isZero(entry) || isNaN(entry) || !isFinite(entry)); } function gaussianElimination(matrix, rowOffset = 0, colOffset = 0) { if (matrix.length < 2) { return true; } if (isRowZero(matrix, rowOffset)) { return false; } colOffset = getFirstNonZeroColumnIndex(matrix, colOffset); if (colOffset < 0) { return false; } if (isZero(matrix[rowOffset][colOffset])) { const row = getFirstNonZeroRowIndex(matrix, rowOffset, colOffset); if (row < 0) { return false; } swapRows(matrix, rowOffset, row); } for (let i = rowOffset + 1; i < matrix.length; i ++) { const multiplier = matrix[i][colOffset] / matrix[rowOffset][colOffset]; for (let ii = colOffset; ii < matrix[0].length; ii ++) { matrix[i][ii] -= (multiplier * matrix[rowOffset][ii]); } } if (rowOffset < matrix.length - 1 && colOffset < matrix[0].length - 1) { return gaussianElimination(matrix, rowOffset + 1, colOffset + 1); } for (let i = rowOffset + 1; i < matrix.length; i ++) { if (isRowZero(matrix, i)) { return false; } } return true; } function isRowZero(matrix, index) { return isVectorZero(matrix[index]); } function swapRows(matrix, from, to) { const tmp = matrix[from]; matrix[from] = matrix[to]; matrix[to] = tmp; } function getFirstNonZeroColumnIndex(matrix, offset) { for (let ii = offset; ii < matrix[0].length; ii ++) { for (let i = 0; i < matrix.length; i ++) { if (matrix[i][ii] != 0) { return ii; } } } return -1; } function getFirstNonZeroRowIndex(matrix, offset, colIndex) { for (let i = offset; i < matrix.length; i ++) { if (isZero(matrix[i][colIndex])) { return i; } } return -1; } function randomMatrix(vectors, length, bound) { const matrix = []; for (let i = 0; i < vectors; i ++) { if (1 / vectors > Math.random()) { matrix.push(vectorZero(length)); continue; } const vector = []; for (let ii = 0; ii < length; ii ++) { vector.push(Math.floor(Math.random() * bound * 2 - bound)); } matrix.push(vector); } return matrix; } function isZero(num) { return num >= -1e-12 && num <= 1e-12; } function vectorZero(length) { return new Array(length).fill(0); } function print(matrix) { for (let i = 0; i < matrix.length; i ++) { console.log(matrix[i]); } }