View on GitHub

marymafa.github.io


layout: post titlte: Pairwise date: 2018-01-19 —

Algirithm Challenge

Pasirwise

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.

Code Explanation:

  1. The variable sum holds the sum of indices.

  2. The outer for loop starts from the first element of arr.

  3. The inner for loop starts from the second element of arr.

  4. If the sum of an element and the element succeeding it is equal to arg.

  5. The sum of the indices of these elements is added to sum.

  6. And use the delete to values after getting the sum of the pairs.

My Approach

I have a funtion titled pairwise that will compare the entities in pairs to judge which of each entity is preferred, or has a greater amount of some quantitative property. I created a variable called sum that will holds the sum of indices and pairs variable that will shallow copy of a portion of an array using slice method.

I have two(2) for loop, the first one is the outer for loop starts form the first element of an array which is index zero(0) and the second one is the inner for loop starts from the second element of arr which is index one(1) up to the last index.

On my test statement i said if pairs index[i] adding with [airs index[2], equals to the argument then return their sum . After getting the sum of both indexes or elements that equalls to the argument , delete those elements to see whether are the remaining pairs, like when adding will equal to the agument.

Finally , its working , and it return an accurate results.

This my piece of code:

function pairwise(arr, arg) { var sum = 0; var paired = arr.slice(); for (var i = 0; i < paired.length; i++) { for ( j=i+1; j< paired.length; j++) { if (paired[i] + paired[j] === arg) { sum += i + j;

           delete paired[i];
           delete paired[j];

        }

    }

}
return sum;