我有一个这样的数组:
[20,40,60,60,20]
要求:将任意两个数字相加,如果结果可被 60 整除,则计数为 1。因此该数组应返回 3 对。 (20,40),(40,20),(60,60)。
这是我写的代码,但它给了我 4 而不是 3
function countPlayList (array) {
let count = 0;
for (let i = 0; i < array.length-1; i++) {
for (let j = 0; j < array.length-1; j++) {
let a = array[i];
let b = array[j];
if (checkPlayTime(a, b) && notDuplicate(i, j)) {
count++;
}
}
}
return count;
}
function checkPlayTime (a, b) {
return Number.isInteger((a + b)/60);
}
function notDuplicate (x, y) {
return x !== y ? true : false;
}
我在这里错过了什么吗?
最佳答案
从 i+1
开始第二个循环因为您已经在第一个循环中获取了第 i 个索引,所以您必须从 i+1
开始遍历。到数组的长度,同时运行两个循环直到 i < array.length
因为你从 index
开始0
function countPlayList (array) {
let count = 0;
for (let i = 0; i < array.length; i++) {
for (let j = i+1; j < array.length; j++) {
let a = array[i];
let b = array[j];
if (checkPlayTime(a, b) && notDuplicate(i, j)) {
count++;
}
}
}
return count;
}
function checkPlayTime (a, b) {
return Number.isInteger((a + b)/60);
}
function notDuplicate (x, y) {
return x !== y ? true : false;
}
console.log(countPlayList([20,40,60,60,20]))
关于javascript - 在数组 JavaScript 中添加所有成对的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59552327/