(function () {
const A = [
[0, 0, 0, 1, 0, 5, 0, 7, 0, 0],
[0, 0, 0, 0, 0, 8, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
function matrixToTriple(A) {
const triples = [];
for (let row = 0; row < A.length; row++) {
for (let col = 0; col < A[row].length; col++) {
if (A[row][col] !== 0) {
triples.push({ row: row + 1, col: col + 1, value: A[row][col] });
}
}
}
return triples;
}
const triples = matrixToTriple(A);
console.log("稀疏矩阵A的三元组表示:");
console.table(triples);
const givenTriples = [
{ row: 1, col: 3, value: 11 },
{ row: 1, col: 5, value: 17 },
{ row: 2, col: 2, value: 25 },
{ row: 4, col: 1, value: 19 },
{ row: 5, col: 4, value: 37 },
{ row: 6, col: 7, value: 50 }
];
function tripleToMatrix(triples) {
if (triples.length === 0) return [];
const maxRow = Math.max(...triples.map(t => t.row));
const maxCol = Math.max(...triples.map(t => t.col));
const matrix = Array.from({ length: maxRow }, () => Array(maxCol).fill(0));
triples.forEach(triple => {
matrix[triple.row - 1][triple.col - 1] = triple.value;
});
return matrix;
}
const matrixFromTriples = tripleToMatrix(givenTriples);
console.log("\n根据给定三元组还原的矩阵直观表示:");
console.table(matrixFromTriples);
})();