简体   繁体   中英

How can you iterate through all the numbers in an array and either add or subtract them so they hit a predetermined value

Let's assume I have two variables. One an array of numbers and the other the number 3. The goal is to iterate through the array of numbers and figure out which pair of numbers can be used to equal the number 3 either by being added together or subtracted.

var numbers = [-1, -1, 4, 2, 3, 5, 0]
var target = 3

for(i = 0; i < numbers.length; i++) {

}

I understand the for loop is going to go through the array of numbers but once I do that I don't understand how I can check every pair and see if they add or subtract to hit the value of 3. Is there a JavaScript method that can help?

Not sure if I understood correctly, but maybe something like this?

var numbers = [-1, -1, 4, 2, 3, 5, 0];
var target = 3;
var pairs = [];

for (i = 0; i < numbers.length; i++) {
    for (j = 0; j < numbers.length; j++) {
        if (j != i) {
            if ((numbers[i] + numbers[j]) == target) {
                pairs.push([numbers[i], numbers[j]]);
                document.write(numbers[i] + " + " + numbers[j] + " = " + target + "<br>");
            }
        }
    }
}

Basically you go through each number in the array, then loop again through all the numbers and check if their sum equals to the target.

You can test it here .

I don't think there is a JavaScript method for this, but this should work:

for(i = 0; i < numbers.length; i++) {
    // calculate the difference
    var diff = target - numbers[i];

    // now: numbers[i] + diff === target
    // do whatever you want with diff
}
for (var i = 0; i < numbers.length-1; i++){
  for (var j = i+1; j < numbers.length; j++){
   if(numbers[i] + numbers[j] == target || Math.abs(numbers[i] - numbers[j]) == target){
   console.log(numbers[i]+" , "+numbers[j]); //Do whatever you want
  }
 }   
}

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