检查数组中数组中任何元素的和是否等于给定值

时间:2018-10-22 23:11:33

标签: javascript arrays

[1,2,3,6], 3 = True <== 1+2=3
[1,2,3,6], 9 = True <== 3+6=9
[1,2,3,6], 5 = True <== 2+3=5
[1,2,3,6], 10 = False <== 1+2, 2+3, 3+6, 6+1 not equal to 10
[6,2,3,1], 10 = False <== 6+2, 2+3, 3+1, 1+6 not equal to 10
[6,3,3,1], 6 = True <== 3+3=6

首选JavaScript
如果给定的sum等于数组中任何两个元素的和,则函数需要返回true;否则函数需要返回false。

3 个答案:

答案 0 :(得分:0)

您可以使用函数some来检查至少一项操作是true

这种方法遵循您的用例

let check = (sum, arr) => arr.concat(arr[0]).some((n, i, a) => (n + a[i+1]) === sum);
    
console.log(check(3, [1,2,3,6]));
console.log(check(9, [1,2,3,6]));
console.log(check(5, [1,2,3,6]));
console.log(check(10, [1,2,3,6]));
console.log(check(10, [6,2,3,1]));
console.log(check(6, [6,3,3,1]));
console.log(check(7, [3,1,2,4]));
console.log(check(7, []));
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果您需要检查该数组中的任何两个值,请遵循以下方法:

let check = (sum, arr) => {
  let inner = arr.concat(arr[0]);
  for (let i = 0, {length} = inner; i < length; i++) {
    for (let j = i + 1, {length} = inner; j < length; j++) {
      if (inner[i] + inner[j] === sum) return true;
    }
  }
  return false;
};
    
console.log(check(3, [1,2,3,6]));
console.log(check(9, [1,2,3,6]));
console.log(check(5, [1,2,3,6]));
console.log(check(10, [1,2,3,6]));
console.log(check(10, [6,2,3,1]));
console.log(check(6, [6,3,3,1]));
console.log(check(7, [3,1,2,4]));
console.log(check(4, [1,1,3,7]));
console.log(check(7, []));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您将不得不遍历值数组。不熟悉javascript,因此这是Java函数中的代码:

public boolean checkSum(){
  int sumValue = 10; //value you want to check, could be passed in as a parameter
  int arr[4] = {1,2,4,6};
  for (int n = 0; n < arr.length; n++){
    for (int x = 0; x < arr.length; x++){
      if ( (arr[n] + arr[x] == sumValue) && (n != x) ){ //need to ensure same slot is being added
        return true;
      }
    }
  }
  return false;
}

希望这会有所帮助!

答案 2 :(得分:0)

这是一种非常简单的方法,它将检查数组中的两个数字是否等于一个值。请注意,这仅允许不同的总和(与自身相加的数字不计算在内)。

function test(n, arr){
   return arr.some((item, i) => arr.slice(i+1).includes(n-item))
}

let arr = [1, 2, 3, 6]

console.log(test(5, arr))   // true 2+3
console.log(test(4, arr))   // true 1+3
console.log(test(12, arr))  // false because 6 + 6 doesn't count
console.log(test(10, arr))  // false no sums

如果数组都是正数,则可以为短路情况添加一个额外的测试,而这种情况可能是不正确的:

 return arr.some((item, i) => n > item && arr.slice(i+1).includes(n-item))

如果要允许数字与它们的总和相加,只需对整个数组进行测试:

 return arr.some((item, i) => arr.includes(n-item))