我正在研究freecodecamp的基本算法挑战。挑战在于返回数组中的最大数字。这是代码。
function largestOfFour(arr) {
// You can do this!
let largestWord = [0,0,0,0];
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length; j++) {
if(arr[i][j] > largestWord[i]) {
largestWord[i] = arr[i][j];
}
}
}
return largestWord;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
我已经通过了三个条件:
largestOfFour([[4,5,1,3],[13,27,18,26],[32,35,37,39],[1000,1001,857,1]])应该返回一个数组。 已通过 maximumOfFour([[13,27,18,26],[4,5,1,3],[32,35,37,39],[1000,1001,857,1]])应该返回[27,5 ,39,1001]。 已通过 maximumOfFour([[4,9,1,3],[13,35,18,26],[32,35,97,39],[1000000,1001,857,1]])应该返回[9,35 ,97,1000000]。
除largeOfFour([[17,23,25,12],[25,7,34,48],[4,-10,18,21],[-72,-3,- 17,-10]])应该返回[25,48,21,-3]。
我哪里出错了?
答案 0 :(得分:1)
所以在您的代码中,您在此代码段中出错了。
if(arr[i][j] > largestWord[i]) {
largestWord[i] = arr[i][j];
}
您忘记的是,您有一个最大的起始值为0,然后将数组元素与该值进行比较。只有超过0的值才能替换。所以我建议只初始化没有值的数组,并对此进行检查
//initialize the array without a value
let largestWord = new Array(4);
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length; j++) {
//also add a check for initial value
if(arr[i][j] > largestWord[i] || largestWord[i] == undefined) {
largestWord[i] = arr[i][j];
}
}
}
答案 1 :(得分:0)
似乎您可以使用.map()
和Math.max()
function largestOfFour(arr) {
return arr.map(x => Math.max(...x));
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));
console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));