Javascript 重构此循环以执行多个迭代
在这里,我试图找到20*20网格中四个对角相邻的数字,它们的乘积是最大的。对角线从左上角到右下角。但是第一个循环有点问题:它没有在数组上迭代。我找不到它是什么Javascript 重构此循环以执行多个迭代,javascript,arrays,for-loop,Javascript,Arrays,For Loop,在这里,我试图找到20*20网格中四个对角相邻的数字,它们的乘积是最大的。对角线从左上角到右下角。但是第一个循环有点问题:它没有在数组上迭代。我找不到它是什么 function fouradjacentFinder(){ let mystring = "08 02 22 97 38 15 ..." let myarray = mystring.split(" ").map(x =>Number(x)); let counter
function fouradjacentFinder(){
let mystring = "08 02 22 97 38 15 ..."
let myarray = mystring.split(" ").map(x =>Number(x));
let counter ;
let max = -Infinity;
for(let i = 0;i<myarray.length;i++){
counter= 0 ;
for(let k =21;;k+21 ){
myarray[i] = myarray[i]*myarray[k];
counter++
if(counter>4){
break;
}
if(myarray[i]>max){
max = myarray[i] ;
}
console.log(max)
}
return max;
}
}
函数fouradjacentFinder(){
让mystring=“08 02 22 97 38 15…”
让myarray=mystring.split(“”.map(x=>Number(x));
让我们来反击;
设max=-无穷大;
for(设i=0;i4){
打破
}
如果(myarray[i]>最大值){
max=myarray[i];
}
console.log(最大值)
}
返回最大值;
}
}
几个问题:
- 缩进已关闭,因此忽略了
语句出现在return
循环中的事实:因此它只执行一次迭代。始终正确缩进代码for
不修改k+21
。您需要执行k
k+=21
独立于myarray[k]
的值,该值不正确。将i
添加到该索引中,或定义i
,使其包含k
的值i
不应迭代到i
,因为在最后几行中,对角线不可能有4个值。循环应该提前停止myarray.length
function fouradjacentFinder(){
let mystring = "08 02 22 97 38 15 ..."
// No need to have an anonymous function wrapper around Number
let myarray = mystring.split(" ").map(Number);
let max = -Infinity;
for (let i = 0; i + 3*21 < myarray.length; i++) { // Limit i
// Better not update myarray[i] and use separate variable
let product = 1;
for (let k = i; k < i+4*21; k += 21) { // fix k
product *= myarray[k];
}
if (product > max){
max = product;
}
}
return max; // outside loop
}
函数fouradjacentFinder(){
让mystring=“08 02 22 97 38 15…”
//不需要对数字进行匿名函数包装
让myarray=mystring.split(“”).map(数字);
设max=-无穷大;
对于(设i=0;i+3*21最大值){
最大值=产品;
}
}
return max;//外部循环
}
非常感谢您,先生。