moonshineOutlaw
moonshineOutlaw

Reputation: 723

Comparing 2 arrays to output total integer

I have 2 arrays of numbers. I want to go through each array and find the number of times 1 number from each array adds up to the particular amount x.

If the particular amount x is reached as many times as another set number n then the function should print 'YES'. If x does not reach the set number of n then the function should print 'NO'.

The values of x , n and both arrays are in a string input. These values have been split into arrays as seen below in the code.

I have set up 2 for loops to run through each array and an if statement that checks for the condition of x meeting n.

The arrays I'm using in this code should print out the result of 'YES' however every time I run the code I'm getting 'NO' ? I've tried tinkering with the code but nothing has worked.

Any idea on where this code is broke and how to fix the problem?

Thanks :)

code:

var input = '2\n3 10\n2 1 3\n7 8 9';

function processData(input) {
   var inputArray = input.split('\n');
   var n = inputArray[1][0];
   var x = inputArray[1].split(' ')[1];
   var arrayA = inputArray[2].split(' ');
   var arrayB = inputArray[3].split(' ');
   var total = 0;

   for(var i = 0; i < arrayA.length; i++) {
      for(var j = 0; j < arrayB.length; j++) {
          if(arrayA[i] + arrayB[j] == x) {
              total = total + 1;
          } if (total == n) {
              return 'YES';
          }
      }
  }
  return 'NO';
}

console.log(processData(input)); 

Upvotes: 2

Views: 67

Answers (1)

Tibos
Tibos

Reputation: 27833

arrayA[i] and arrayB[j] are strings, so arrayA[i] + arrayB[j] will be the concatenation of them (ex: '2' + '3' === '23').

If your logic is correct (i didn't quite understand what you are trying to do), it should be enough to convert them to numbers before adding them, using parseInt or some other method:

if(+arrayA[i] + (+arrayB[j]) == +x) { // used unary + to convert to number
          total = total + 1;
      } if (total == n) {
          return 'YES';
      }

PS: A cleaner version would be to convert each string in the array to number, but that involves more than adding 3 characters to your code.

PS2: You have a weird way of getting the input data. If you get it from another place in your JS code, you could simply pass it as an object with the relevant structure, otherwise you could pass it around in a more ... common format, like JSON.

Upvotes: 2

Related Questions