gpt4 book ai didi

javascript - 如何在 Matrix 类中重构大量类似的嵌套循环?

转载 作者:行者123 更新时间:2023-11-28 14:15:25 26 4
gpt4 key购买 nike

如何正确重构我的 Matrix 类,其中我在该类中使用的几乎所有方法都有双重嵌套循环,它们看起来几乎完全相同?

以下是我希望包含在此类中的众多方法中的两个。如果我找不到更好的方法来处理这个问题,那么时间将会变得不必要的漫长。

randomize() {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.matrix[i][j] = Math.random();
}
}
}

add(n) {
if (n instanceof Matrix) {
for (let i = 0; i < this.matrix.length; i++) {
for (let j = 0; j < this.matrix[i].length; j++) {
this.matrix[i][j] += n.matrix[i][j];
}
}
} else {
for (let i = 0; i < this.matrix.length; i++) {
for (let j = 0; j < this.matrix[i].length; j++) {
this.matrix[i][j] += n;
}
}
}
}

最佳答案

与 Barmar 的答案类似,只是风格不同:

// Specify the limits for i, j, and then pass in a function
// which takes the index parameters.
function loop(iMax, jMax, fn) {
for (let i = 0; i < iMax; i++) {
for (let j = 0; j < jMax; j++) {
fn(i, j);
}
}
}

function randomize() {
loop(this.rows, this.columns, (i, j) => {
this.matrix[i][j] = Math.random();
});
}

function add(n) {
if (n instanceof Matrix) {
loop(this.matrix.length, this.matrix[0].length, (i, j) => {
this.matrix[i][j] += n[i][j];
});
}
}

这种更通用的方法允许您对循环索引执行任何您想要的操作。您可以进行重新分配,或者可以注销矩阵值,或者将它们分配给新矩阵。

loop(this.rows, this.cols, (i, j) => {
console.log(this.matrix[i][j]);
});
loop(this.rows, this.cols, (i, j) => {
that.matrix = this.matrix[i][j];
});

关于javascript - 如何在 Matrix 类中重构大量类似的嵌套循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57700165/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com