简体   繁体   中英

Count number of times two elements in array are less than or equal to a sum value - Javascript

I have this JS function that finds the number of times two elements equal to a sum value. I am trying to modify this so that the condition isn't only when the two elements are equal to sum, but when it's less than the sum value as well.

var array = [-10, -8, -1, 0, 1, 6, 10];
var sum = 16;

function findLessThanOrEqualSum(array, sum){
  var count = 0;
  var map = {};
  for(var i = 0; i<array.length; i++){
    var temp = sum - array[i]; //This right here only accounts for when two elements = sum

    if(temp >= 0 && map[temp]){
      console.log(sum + " " + array[i] + " " + temp);
      count++;
    }
    map[array[i]] = true;
  }
  console.log(count);
}

findLessThanOrEqualSum(array, sum);

How would I change this condition var temp = sum - array[i]; so that it accounts for the instances temp is <= sum - array[i]; ?

I've tried assigned a second temp variable that will hold all the values for when temp <= sum - array[i]; but I was not successful. Any help would be appreciated.

You're doing it in a very convoluted way. Just use nested loops that add two array elements, and test if they're less than the sum.

 var array = [-10, -8, -1, 0, 1, 6, 10, 11, 8, 9]; var sum = 16; function findLessThanOrEqualSum(array, sum) { var count = 0; for (var i = 0; i < array.length - 1; i++) { for (var j = i + 1; j < array.length; j++) { if (array[i] + array[j] < sum) { console.log(sum + " " + array[i] + " " + array[j]); count++; } } } console.log(count); } findLessThanOrEqualSum(array, sum); 

The way you're doing it works for the equal condition because you can look for a specific key in map . But there's no specific thing to look for when you have an comparison condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM