javascript - 在数组 JavaScript 中添加所有成对的数字

标签 javascript arrays duplicates nested-loops

我有一个这样的数组:
[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/

相关文章:

python - 根据传递给这些元素的函数的返回值更改 numpy 数组的元素

没有数组的java随机数生成器

javascript - 在 ExpressJS 中运行多个应用程序

javascript - 无法在另一个函数中调用函数

javascript - Javascript 中回调数组的不同参数

python - 查找列表中的重复元素

javascript - 减少数组中的嵌套对象键值

php - 在 jquery 脚本中获取页面加载的 ID

javascript - 访问网站时如何查找浏览器发出的所有 JavaScript 请求

Java - 数组元素的排列 - 解释清楚