js实现方阵


使用 JavaScript 实现方阵
在 JavaScript 中,方阵通常是一个二维数组,其中行数和列数相等。以下是几种常见的方阵实现方法:
创建 n×n 方阵
function createSquareMatrix(n) {
const matrix = [];
for (let i = 0; i < n; i++) {
matrix[i] = [];
for (let j = 0; j < n; j++) {
matrix[i][j] = 0; // 初始化为0
}
}
return matrix;
}
const size = 3;
const squareMatrix = createSquareMatrix(size);
console.log(squareMatrix);
填充对角线
function fillDiagonal(matrix, value) {
for (let i = 0; i < matrix.length; i++) {
matrix[i][i] = value;
}
return matrix;
}
const matrix = createSquareMatrix(4);
fillDiagonal(matrix, 1);
console.log(matrix);
方阵转置
function transpose(matrix) {
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < i; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
return matrix;
}
const original = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const transposed = transpose(original);
console.log(transposed);
方阵乘法
function multiplyMatrices(a, b) {
const n = a.length;
const result = createSquareMatrix(n);
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
let sum = 0;
for (let k = 0; k < n; k++) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}
const matrixA = [
[1, 2],
[3, 4]
];
const matrixB = [
[5, 6],
[7, 8]
];
const product = multiplyMatrices(matrixA, matrixB);
console.log(product);
生成螺旋方阵
function generateSpiralMatrix(n) {
const matrix = createSquareMatrix(n);
let num = 1;
let top = 0, bottom = n - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) {
matrix[top][i] = num++;
}
top++;
for (let i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;
for (let i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
bottom--;
for (let i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
}
return matrix;
}
const spiral = generateSpiralMatrix(4);
console.log(spiral);
这些示例展示了 JavaScript 中实现方阵的基本操作,包括创建、填充、转置、乘法以及生成特殊模式的方阵。可以根据具体需求调整这些函数。






