Free Code Camp - PairwiseFind the max. difference between two array elements a[j] and a[i] such that j > iExtract higher value of pair from JavaScript arrayPairwise programming challenge - Free code campFinding an equilibrium index in an int arrayHackerRank university codesprint array constructionFind all triplets in array that add up to a given sumThree sum using binary searchShuffling an array keeping some elements fixedFind value that occurs in odd number of elementsSimple function returning 1 if the Mean = Mode, or 0 if not

Which Article Helped Get Rid of Technobabble in RPGs?

Plot of a tornado shape like surface

Change the color of a single dot in `ddot` symbol

Why is it that I can sometimes guess the next note?

How could a planet have erratic days?

What is Cash Advance APR?

How to get directions in deep space?

Why is so much work done on numerical verification of the Riemann Hypothesis?

What does Apple's new App Store requirement mean

Is this toilet slogan correct usage of the English language?

Does "he squandered his car on drink" sound natural?

How can ping know if my host is down

What is the highest possible scrabble score for placing a single tile

What is the English pronunciation of "pain au chocolat"?

"It doesn't matter" or "it won't matter"?

Quoting Keynes in a lecture

I found an audio circuit and I built it just fine, but I find it a bit too quiet. How do I amplify the output so that it is a bit louder?

Why can't the Brexit deadlock in the UK parliament be solved with a plurality vote?

Mimic lecturing on blackboard, facing audience

15% tax on $7.5k earnings. Is that right?

What is the difference between lands and mana?

The IT department bottlenecks progress, how should I handle this?

It grows, but water kills it

Is it allowed to activate the ability of multiple planeswalkers in a single turn?



Free Code Camp - Pairwise


Find the max. difference between two array elements a[j] and a[i] such that j > iExtract higher value of pair from JavaScript arrayPairwise programming challenge - Free code campFinding an equilibrium index in an int arrayHackerRank university codesprint array constructionFind all triplets in array that add up to a given sumThree sum using binary searchShuffling an array keeping some elements fixedFind value that occurs in odd number of elementsSimple function returning 1 if the Mean = Mode, or 0 if not













6












$begingroup$


I'm working through the Free Code Camp syllabus and I'm on to Intermediate JavaScript Algorithms. This Pairwise problem was the last challenge in that section. The section came just after "Object Oriented JavaScript." So I figured they were looking for an OO solution, but the instructions included a link to MDN's array.reduce(). My solution doesn't use array.reduce() and I'd really appreciate some feedback on what I could have done better to make my code more compact and efficient. It feels a little clunky but passes all the tests.



The instructions




Return the sum of all indices of elements of 'arr' that can be paired
with one other element to form a sum that equals the value in the
second argument 'arg'. If multiple sums are possible, return the
smallest sum. Once an element has been used, it cannot be reused to
pair with another.



For example, pairwise([1, 4, 2, 3, 0, 5], 7) should return 11 because
4, 2, 3 and 5 can be paired with each other to equal 7.



pairwise([1, 3, 2, 4], 4) would only equal 1, because only the first
two elements can be paired to equal 4, and the first element has an
index of 0!



Remember to use RSAP if you get stuck. Try to pair program. Write your
own code.



Here are some helpful links:



Array.reduce()



My Solution



function pairwise(arr, arg) 
this.objects = [];
var total = 0;

function Element(value, index)
this.value = value;
this.index = index;
this.used = 0;


for (var i = 0; i < arr.length; i++)
this.objects.push(new Element(arr[i], i));


for (var j = 0; j < objects.length; j++)
if (objects[j].used === 0)
for (var k = 0; k < objects.length; k++)
if (objects[k].used === 0 && objects[k].index != objects[j].index)
if (arg - objects[j].value == objects[k].value)
total = total + objects[j].index + objects[k].index;
objects[j].used = 1;
objects[k].used = 1;
break;






return total;


pairwise([1,1,1], 2);









share|improve this question











$endgroup$











  • $begingroup$
    Shouldn't the first one return a 4? The instruction did say "If multiple sums are possible, return the smallest sum." and nothing about when multiple sums can be added together or not.
    $endgroup$
    – Joseph
    Jul 30 '15 at 17:04















6












$begingroup$


I'm working through the Free Code Camp syllabus and I'm on to Intermediate JavaScript Algorithms. This Pairwise problem was the last challenge in that section. The section came just after "Object Oriented JavaScript." So I figured they were looking for an OO solution, but the instructions included a link to MDN's array.reduce(). My solution doesn't use array.reduce() and I'd really appreciate some feedback on what I could have done better to make my code more compact and efficient. It feels a little clunky but passes all the tests.



The instructions




Return the sum of all indices of elements of 'arr' that can be paired
with one other element to form a sum that equals the value in the
second argument 'arg'. If multiple sums are possible, return the
smallest sum. Once an element has been used, it cannot be reused to
pair with another.



For example, pairwise([1, 4, 2, 3, 0, 5], 7) should return 11 because
4, 2, 3 and 5 can be paired with each other to equal 7.



pairwise([1, 3, 2, 4], 4) would only equal 1, because only the first
two elements can be paired to equal 4, and the first element has an
index of 0!



Remember to use RSAP if you get stuck. Try to pair program. Write your
own code.



Here are some helpful links:



Array.reduce()



My Solution



function pairwise(arr, arg) 
this.objects = [];
var total = 0;

function Element(value, index)
this.value = value;
this.index = index;
this.used = 0;


for (var i = 0; i < arr.length; i++)
this.objects.push(new Element(arr[i], i));


for (var j = 0; j < objects.length; j++)
if (objects[j].used === 0)
for (var k = 0; k < objects.length; k++)
if (objects[k].used === 0 && objects[k].index != objects[j].index)
if (arg - objects[j].value == objects[k].value)
total = total + objects[j].index + objects[k].index;
objects[j].used = 1;
objects[k].used = 1;
break;






return total;


pairwise([1,1,1], 2);









share|improve this question











$endgroup$











  • $begingroup$
    Shouldn't the first one return a 4? The instruction did say "If multiple sums are possible, return the smallest sum." and nothing about when multiple sums can be added together or not.
    $endgroup$
    – Joseph
    Jul 30 '15 at 17:04













6












6








6


1



$begingroup$


I'm working through the Free Code Camp syllabus and I'm on to Intermediate JavaScript Algorithms. This Pairwise problem was the last challenge in that section. The section came just after "Object Oriented JavaScript." So I figured they were looking for an OO solution, but the instructions included a link to MDN's array.reduce(). My solution doesn't use array.reduce() and I'd really appreciate some feedback on what I could have done better to make my code more compact and efficient. It feels a little clunky but passes all the tests.



The instructions




Return the sum of all indices of elements of 'arr' that can be paired
with one other element to form a sum that equals the value in the
second argument 'arg'. If multiple sums are possible, return the
smallest sum. Once an element has been used, it cannot be reused to
pair with another.



For example, pairwise([1, 4, 2, 3, 0, 5], 7) should return 11 because
4, 2, 3 and 5 can be paired with each other to equal 7.



pairwise([1, 3, 2, 4], 4) would only equal 1, because only the first
two elements can be paired to equal 4, and the first element has an
index of 0!



Remember to use RSAP if you get stuck. Try to pair program. Write your
own code.



Here are some helpful links:



Array.reduce()



My Solution



function pairwise(arr, arg) 
this.objects = [];
var total = 0;

function Element(value, index)
this.value = value;
this.index = index;
this.used = 0;


for (var i = 0; i < arr.length; i++)
this.objects.push(new Element(arr[i], i));


for (var j = 0; j < objects.length; j++)
if (objects[j].used === 0)
for (var k = 0; k < objects.length; k++)
if (objects[k].used === 0 && objects[k].index != objects[j].index)
if (arg - objects[j].value == objects[k].value)
total = total + objects[j].index + objects[k].index;
objects[j].used = 1;
objects[k].used = 1;
break;






return total;


pairwise([1,1,1], 2);









share|improve this question











$endgroup$




I'm working through the Free Code Camp syllabus and I'm on to Intermediate JavaScript Algorithms. This Pairwise problem was the last challenge in that section. The section came just after "Object Oriented JavaScript." So I figured they were looking for an OO solution, but the instructions included a link to MDN's array.reduce(). My solution doesn't use array.reduce() and I'd really appreciate some feedback on what I could have done better to make my code more compact and efficient. It feels a little clunky but passes all the tests.



The instructions




Return the sum of all indices of elements of 'arr' that can be paired
with one other element to form a sum that equals the value in the
second argument 'arg'. If multiple sums are possible, return the
smallest sum. Once an element has been used, it cannot be reused to
pair with another.



For example, pairwise([1, 4, 2, 3, 0, 5], 7) should return 11 because
4, 2, 3 and 5 can be paired with each other to equal 7.



pairwise([1, 3, 2, 4], 4) would only equal 1, because only the first
two elements can be paired to equal 4, and the first element has an
index of 0!



Remember to use RSAP if you get stuck. Try to pair program. Write your
own code.



Here are some helpful links:



Array.reduce()



My Solution



function pairwise(arr, arg) 
this.objects = [];
var total = 0;

function Element(value, index)
this.value = value;
this.index = index;
this.used = 0;


for (var i = 0; i < arr.length; i++)
this.objects.push(new Element(arr[i], i));


for (var j = 0; j < objects.length; j++)
if (objects[j].used === 0)
for (var k = 0; k < objects.length; k++)
if (objects[k].used === 0 && objects[k].index != objects[j].index)
if (arg - objects[j].value == objects[k].value)
total = total + objects[j].index + objects[k].index;
objects[j].used = 1;
objects[k].used = 1;
break;






return total;


pairwise([1,1,1], 2);






javascript algorithm object-oriented array






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 29 '15 at 16:45









Jamal

30.4k11121227




30.4k11121227










asked Jul 29 '15 at 11:03









John BehanJohn Behan

1335




1335











  • $begingroup$
    Shouldn't the first one return a 4? The instruction did say "If multiple sums are possible, return the smallest sum." and nothing about when multiple sums can be added together or not.
    $endgroup$
    – Joseph
    Jul 30 '15 at 17:04
















  • $begingroup$
    Shouldn't the first one return a 4? The instruction did say "If multiple sums are possible, return the smallest sum." and nothing about when multiple sums can be added together or not.
    $endgroup$
    – Joseph
    Jul 30 '15 at 17:04















$begingroup$
Shouldn't the first one return a 4? The instruction did say "If multiple sums are possible, return the smallest sum." and nothing about when multiple sums can be added together or not.
$endgroup$
– Joseph
Jul 30 '15 at 17:04




$begingroup$
Shouldn't the first one return a 4? The instruction did say "If multiple sums are possible, return the smallest sum." and nothing about when multiple sums can be added together or not.
$endgroup$
– Joseph
Jul 30 '15 at 17:04










7 Answers
7






active

oldest

votes


















3












$begingroup$

I looked through your code and it is a valid solution, but you could reduce your code base by better leveraging the functions that JavaScript already provides, such as Array.prototype.indexOf().



For example, instead of building a new class-like-function (Element) to track the appearance of a certain index, I simply made a deep copy of the the initial array and parsed it with indexOf().



Moreover, in your code, when you first declare this.objects = [], this actually refers to the global scope (window object). As you can see, you are calling pairwise without building a new instance (new keyword). In this case, thus the this keyword is bound to the global window object.



Please find below my take on it:



function pairwise(arr, arg) 

var result = 0,
newArr = [],
//Used to hold the indices that we have already used to form our sum
indices = [];

//Loop through arr and create a deep copy of it in newArr
for(var k = 0; k < arr.length; k++)
newArr.push(arr[k]);


//Loop through arr
for(var i = 0; i < arr.length; i++)

//Loop through newArr
for(var j = 0; j < newArr.length; j++)
//Since we want to add different elements of the array, we want to avoid adding the same element
if(i !== j)
//If the sum of two elements is equal to arg AND the indices that we have in i and j are not part of the indices array
//Indices array is used to hold the already used indices, thus ensuring the accurate parsing of the parameters
if(arr[i] + newArr[j] === arg && indices.indexOf(i) === -1 && indices.indexOf(j) === -1)
//Sum the indices up
result += i + j;
//Push the indices in the indices array in order to not use them in further iterations
indices.push(i, j);





return result;


pairwise([1,4,2,3,0,5], 7);





share|improve this answer









$endgroup$












  • $begingroup$
    Hi Vlad—thanks for solution. I am going through your code to try to learn from it. Could you explain how if(i !== j) the first conditional, is comparing anything but the iterators?
    $endgroup$
    – Antonio Pavicevac-Ortiz
    May 9 '16 at 14:57







  • 1




    $begingroup$
    In my solution, newArr is a deep copy of the arr initially passed to the pairwise function. Thus, when the two iterator variables (i & j) have the same value, while iterating through different copies of the same object, they would actually add up the exact same number of the array, which is not a valid case for the aforementioned scenario.
    $endgroup$
    – vladzam
    May 10 '16 at 12:44


















2












$begingroup$

Vlad Z answer is correct but freecodecamp has weird wording on this problem. I used a similar answer but was failing on this test:



expect(pairwise([0, 0, 0, 0, 1, 1], 1)).to.equal(10);


My problem and the problem with Vlad Zs solution is that 0,1 -> indexes (0 and 4) and 0,1 indexes(1 and 5) are both acceptable and should return 10.



I would use Vlad's solution but sub in this function instead of indexOf === -1 to check if a pair exists already:



function checkPairExists(value,position,pairsArray)
for(var i = 0; i < pairsArray.length; i++)
if (pairsArray[i].value === value && pairsArray[i].position === position)
return true;


return false;






share|improve this answer











$endgroup$




















    2












    $begingroup$

    This function implementation uses the "reduce" method to get the sum of the indexes and it fullfills all Free Code Camp tests.



    function pairwise(arr, arg) 
    return arr.reduce((sum, value1, index1) =>
    arr.slice(index1 + 1).forEach((value2, index2) =>
    if (arr[index1] + arr[index1 + 1 + index2] === arg)
    arr[index1] = arr[index1 + 1 + index2] = NaN;
    sum += index1 + index1 + 1 + index2;

    );
    return sum;
    , 0);






    share|improve this answer









    $endgroup$




















      2












      $begingroup$

      I came to the same conclusion as Piotr, but with a slight improvement - dropping one more un-necessary check. See comments in code below:



      function pairwise(arr, arg) 
      var sum = 0;

      for (var i=0; i < arr.length - 1; i++)
      for (var j=i+1; j < arr.length; j++)
      //No need to check for less than arg, used elements are naturally eliminated
      if (arr[i] + arr[j] === arg)
      sum += i + j;
      arr[i] = arr[j] = arg + 1; //Set the used elements to higher than arg e.g. arg + 1




      return sum;


      pairwise([1,4,2,3,0,5], 7);





      share|improve this answer









      $endgroup$




















        1












        $begingroup$

        The requirements are broken down into:



        • Return the sum of all indices of elements of 'arr' that can be paired with one other element to form a sum that equals the value in the second argument 'arg'.

        • If multiple sums are possible, return the smallest sum. Once an element has been used

        • Once an element has been used, it cannot be reused to pair with another.

        The first bullet point is easy enough to understand. We find pairs that sum up to the total, and sum up the indices.



        However, your example contradicts the second bullet point. If multiple sums are found, it should return the smallest. 4 and 3 are 1 and 3 which results to 4. 2 and 5 are 2 and 5 which results to 7. The result should be 4 in the first example.



        So here's my take on it






        function pairwise(arr, total) 
        // For each item in the array
        var sums = arr.reduce(function (indexSum, firstNumber, firstIndex)
        // Collect the pair's index which causes the numbers to sum to total
        var secondIndices = arr.slice(firstIndex + 1).reduce(function (secondIndices, secondNumber, i)
        if (firstNumber + secondNumber === total) secondIndices.push(firstIndex + i + 1);
        return secondIndices;
        , []);
        // Add to our collection the sum this iteration's index and
        // the pair indices
        return indexSum.concat(secondIndices.map(function (secondIndex)
        return secondIndex + firstIndex
        ));
        , []);
        // In all the items, find the smallest sum
        return Math.min.apply(null, sums);


        console.log(pairwise([1, 4, 2, 3, 0, 5], 7));
        console.log(pairwise([1, 3, 2, 4], 4));





        Regarding bullet point 3, I would care less if a number was reused, like in the case of 6 in [4, 4, 2] or say [4, 2, 9, 9, 4] because any number that's going to pair with it after the first established pair will have a higher index sum anyways.






        share|improve this answer









        $endgroup$












        • $begingroup$
          Thanks for the great reply, the way I read the second requirement - returning smallest sum, was that if the target could be reached by two calculations sharing one number then we should use the calculation whose sum of indices is smallest. For example: pairwise([0,1,1], 1) should return 1, even though it is possible to use the last number in the array with the 0 to get an answer of 2, we should use the smallest index sum. Thanks again though and you managed to use array.reduce()! I would never have gotten that.
          $endgroup$
          – John Behan
          Jul 31 '15 at 6:40



















        1












        $begingroup$

        The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
        http://codepen.io/PiotrBerebecki/pen/RRGaBZ.



        function pairwise(arr, arg) 
        var sum = 0;
        for (var i=0; i<arr.length-1; i++)
        for (var j=i+1; j<arr.length; j++)
        if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg)
        sum += i+j;
        arr[i] = arr[j] = NaN;



        return sum;


        console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6


        Under the hood:



        1. Start looping from the element with index (i) = 0.

        2. Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.

        3. If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.

        4. If the pair has been found then change their values to NaN to avoid further checks and duplication.





        share|improve this answer











        $endgroup$




















          0












          $begingroup$

          Old forum but wanted to contribute an ES6 solution



           function pairwise(arr, arg) 
          let sum=0;

          // ES6
          for(let i in arr)
          for(let j in arr)
          if(i!=j)
          if ((arr[i]+arr[j]) === arg)
          sum += (Number(i)+Number(j));
          arr[i] = arr[j] = arg+1;




          return sum;


          pairwise([1, 4, 2, 3, 0, 5], 7)





          share|improve this answer








          New contributor




          Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$












            Your Answer





            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f98448%2ffree-code-camp-pairwise%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3












            $begingroup$

            I looked through your code and it is a valid solution, but you could reduce your code base by better leveraging the functions that JavaScript already provides, such as Array.prototype.indexOf().



            For example, instead of building a new class-like-function (Element) to track the appearance of a certain index, I simply made a deep copy of the the initial array and parsed it with indexOf().



            Moreover, in your code, when you first declare this.objects = [], this actually refers to the global scope (window object). As you can see, you are calling pairwise without building a new instance (new keyword). In this case, thus the this keyword is bound to the global window object.



            Please find below my take on it:



            function pairwise(arr, arg) 

            var result = 0,
            newArr = [],
            //Used to hold the indices that we have already used to form our sum
            indices = [];

            //Loop through arr and create a deep copy of it in newArr
            for(var k = 0; k < arr.length; k++)
            newArr.push(arr[k]);


            //Loop through arr
            for(var i = 0; i < arr.length; i++)

            //Loop through newArr
            for(var j = 0; j < newArr.length; j++)
            //Since we want to add different elements of the array, we want to avoid adding the same element
            if(i !== j)
            //If the sum of two elements is equal to arg AND the indices that we have in i and j are not part of the indices array
            //Indices array is used to hold the already used indices, thus ensuring the accurate parsing of the parameters
            if(arr[i] + newArr[j] === arg && indices.indexOf(i) === -1 && indices.indexOf(j) === -1)
            //Sum the indices up
            result += i + j;
            //Push the indices in the indices array in order to not use them in further iterations
            indices.push(i, j);





            return result;


            pairwise([1,4,2,3,0,5], 7);





            share|improve this answer









            $endgroup$












            • $begingroup$
              Hi Vlad—thanks for solution. I am going through your code to try to learn from it. Could you explain how if(i !== j) the first conditional, is comparing anything but the iterators?
              $endgroup$
              – Antonio Pavicevac-Ortiz
              May 9 '16 at 14:57







            • 1




              $begingroup$
              In my solution, newArr is a deep copy of the arr initially passed to the pairwise function. Thus, when the two iterator variables (i & j) have the same value, while iterating through different copies of the same object, they would actually add up the exact same number of the array, which is not a valid case for the aforementioned scenario.
              $endgroup$
              – vladzam
              May 10 '16 at 12:44















            3












            $begingroup$

            I looked through your code and it is a valid solution, but you could reduce your code base by better leveraging the functions that JavaScript already provides, such as Array.prototype.indexOf().



            For example, instead of building a new class-like-function (Element) to track the appearance of a certain index, I simply made a deep copy of the the initial array and parsed it with indexOf().



            Moreover, in your code, when you first declare this.objects = [], this actually refers to the global scope (window object). As you can see, you are calling pairwise without building a new instance (new keyword). In this case, thus the this keyword is bound to the global window object.



            Please find below my take on it:



            function pairwise(arr, arg) 

            var result = 0,
            newArr = [],
            //Used to hold the indices that we have already used to form our sum
            indices = [];

            //Loop through arr and create a deep copy of it in newArr
            for(var k = 0; k < arr.length; k++)
            newArr.push(arr[k]);


            //Loop through arr
            for(var i = 0; i < arr.length; i++)

            //Loop through newArr
            for(var j = 0; j < newArr.length; j++)
            //Since we want to add different elements of the array, we want to avoid adding the same element
            if(i !== j)
            //If the sum of two elements is equal to arg AND the indices that we have in i and j are not part of the indices array
            //Indices array is used to hold the already used indices, thus ensuring the accurate parsing of the parameters
            if(arr[i] + newArr[j] === arg && indices.indexOf(i) === -1 && indices.indexOf(j) === -1)
            //Sum the indices up
            result += i + j;
            //Push the indices in the indices array in order to not use them in further iterations
            indices.push(i, j);





            return result;


            pairwise([1,4,2,3,0,5], 7);





            share|improve this answer









            $endgroup$












            • $begingroup$
              Hi Vlad—thanks for solution. I am going through your code to try to learn from it. Could you explain how if(i !== j) the first conditional, is comparing anything but the iterators?
              $endgroup$
              – Antonio Pavicevac-Ortiz
              May 9 '16 at 14:57







            • 1




              $begingroup$
              In my solution, newArr is a deep copy of the arr initially passed to the pairwise function. Thus, when the two iterator variables (i & j) have the same value, while iterating through different copies of the same object, they would actually add up the exact same number of the array, which is not a valid case for the aforementioned scenario.
              $endgroup$
              – vladzam
              May 10 '16 at 12:44













            3












            3








            3





            $begingroup$

            I looked through your code and it is a valid solution, but you could reduce your code base by better leveraging the functions that JavaScript already provides, such as Array.prototype.indexOf().



            For example, instead of building a new class-like-function (Element) to track the appearance of a certain index, I simply made a deep copy of the the initial array and parsed it with indexOf().



            Moreover, in your code, when you first declare this.objects = [], this actually refers to the global scope (window object). As you can see, you are calling pairwise without building a new instance (new keyword). In this case, thus the this keyword is bound to the global window object.



            Please find below my take on it:



            function pairwise(arr, arg) 

            var result = 0,
            newArr = [],
            //Used to hold the indices that we have already used to form our sum
            indices = [];

            //Loop through arr and create a deep copy of it in newArr
            for(var k = 0; k < arr.length; k++)
            newArr.push(arr[k]);


            //Loop through arr
            for(var i = 0; i < arr.length; i++)

            //Loop through newArr
            for(var j = 0; j < newArr.length; j++)
            //Since we want to add different elements of the array, we want to avoid adding the same element
            if(i !== j)
            //If the sum of two elements is equal to arg AND the indices that we have in i and j are not part of the indices array
            //Indices array is used to hold the already used indices, thus ensuring the accurate parsing of the parameters
            if(arr[i] + newArr[j] === arg && indices.indexOf(i) === -1 && indices.indexOf(j) === -1)
            //Sum the indices up
            result += i + j;
            //Push the indices in the indices array in order to not use them in further iterations
            indices.push(i, j);





            return result;


            pairwise([1,4,2,3,0,5], 7);





            share|improve this answer









            $endgroup$



            I looked through your code and it is a valid solution, but you could reduce your code base by better leveraging the functions that JavaScript already provides, such as Array.prototype.indexOf().



            For example, instead of building a new class-like-function (Element) to track the appearance of a certain index, I simply made a deep copy of the the initial array and parsed it with indexOf().



            Moreover, in your code, when you first declare this.objects = [], this actually refers to the global scope (window object). As you can see, you are calling pairwise without building a new instance (new keyword). In this case, thus the this keyword is bound to the global window object.



            Please find below my take on it:



            function pairwise(arr, arg) 

            var result = 0,
            newArr = [],
            //Used to hold the indices that we have already used to form our sum
            indices = [];

            //Loop through arr and create a deep copy of it in newArr
            for(var k = 0; k < arr.length; k++)
            newArr.push(arr[k]);


            //Loop through arr
            for(var i = 0; i < arr.length; i++)

            //Loop through newArr
            for(var j = 0; j < newArr.length; j++)
            //Since we want to add different elements of the array, we want to avoid adding the same element
            if(i !== j)
            //If the sum of two elements is equal to arg AND the indices that we have in i and j are not part of the indices array
            //Indices array is used to hold the already used indices, thus ensuring the accurate parsing of the parameters
            if(arr[i] + newArr[j] === arg && indices.indexOf(i) === -1 && indices.indexOf(j) === -1)
            //Sum the indices up
            result += i + j;
            //Push the indices in the indices array in order to not use them in further iterations
            indices.push(i, j);





            return result;


            pairwise([1,4,2,3,0,5], 7);






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 31 '15 at 9:03









            vladzamvladzam

            1461




            1461











            • $begingroup$
              Hi Vlad—thanks for solution. I am going through your code to try to learn from it. Could you explain how if(i !== j) the first conditional, is comparing anything but the iterators?
              $endgroup$
              – Antonio Pavicevac-Ortiz
              May 9 '16 at 14:57







            • 1




              $begingroup$
              In my solution, newArr is a deep copy of the arr initially passed to the pairwise function. Thus, when the two iterator variables (i & j) have the same value, while iterating through different copies of the same object, they would actually add up the exact same number of the array, which is not a valid case for the aforementioned scenario.
              $endgroup$
              – vladzam
              May 10 '16 at 12:44
















            • $begingroup$
              Hi Vlad—thanks for solution. I am going through your code to try to learn from it. Could you explain how if(i !== j) the first conditional, is comparing anything but the iterators?
              $endgroup$
              – Antonio Pavicevac-Ortiz
              May 9 '16 at 14:57







            • 1




              $begingroup$
              In my solution, newArr is a deep copy of the arr initially passed to the pairwise function. Thus, when the two iterator variables (i & j) have the same value, while iterating through different copies of the same object, they would actually add up the exact same number of the array, which is not a valid case for the aforementioned scenario.
              $endgroup$
              – vladzam
              May 10 '16 at 12:44















            $begingroup$
            Hi Vlad—thanks for solution. I am going through your code to try to learn from it. Could you explain how if(i !== j) the first conditional, is comparing anything but the iterators?
            $endgroup$
            – Antonio Pavicevac-Ortiz
            May 9 '16 at 14:57





            $begingroup$
            Hi Vlad—thanks for solution. I am going through your code to try to learn from it. Could you explain how if(i !== j) the first conditional, is comparing anything but the iterators?
            $endgroup$
            – Antonio Pavicevac-Ortiz
            May 9 '16 at 14:57





            1




            1




            $begingroup$
            In my solution, newArr is a deep copy of the arr initially passed to the pairwise function. Thus, when the two iterator variables (i & j) have the same value, while iterating through different copies of the same object, they would actually add up the exact same number of the array, which is not a valid case for the aforementioned scenario.
            $endgroup$
            – vladzam
            May 10 '16 at 12:44




            $begingroup$
            In my solution, newArr is a deep copy of the arr initially passed to the pairwise function. Thus, when the two iterator variables (i & j) have the same value, while iterating through different copies of the same object, they would actually add up the exact same number of the array, which is not a valid case for the aforementioned scenario.
            $endgroup$
            – vladzam
            May 10 '16 at 12:44













            2












            $begingroup$

            Vlad Z answer is correct but freecodecamp has weird wording on this problem. I used a similar answer but was failing on this test:



            expect(pairwise([0, 0, 0, 0, 1, 1], 1)).to.equal(10);


            My problem and the problem with Vlad Zs solution is that 0,1 -> indexes (0 and 4) and 0,1 indexes(1 and 5) are both acceptable and should return 10.



            I would use Vlad's solution but sub in this function instead of indexOf === -1 to check if a pair exists already:



            function checkPairExists(value,position,pairsArray)
            for(var i = 0; i < pairsArray.length; i++)
            if (pairsArray[i].value === value && pairsArray[i].position === position)
            return true;


            return false;






            share|improve this answer











            $endgroup$

















              2












              $begingroup$

              Vlad Z answer is correct but freecodecamp has weird wording on this problem. I used a similar answer but was failing on this test:



              expect(pairwise([0, 0, 0, 0, 1, 1], 1)).to.equal(10);


              My problem and the problem with Vlad Zs solution is that 0,1 -> indexes (0 and 4) and 0,1 indexes(1 and 5) are both acceptable and should return 10.



              I would use Vlad's solution but sub in this function instead of indexOf === -1 to check if a pair exists already:



              function checkPairExists(value,position,pairsArray)
              for(var i = 0; i < pairsArray.length; i++)
              if (pairsArray[i].value === value && pairsArray[i].position === position)
              return true;


              return false;






              share|improve this answer











              $endgroup$















                2












                2








                2





                $begingroup$

                Vlad Z answer is correct but freecodecamp has weird wording on this problem. I used a similar answer but was failing on this test:



                expect(pairwise([0, 0, 0, 0, 1, 1], 1)).to.equal(10);


                My problem and the problem with Vlad Zs solution is that 0,1 -> indexes (0 and 4) and 0,1 indexes(1 and 5) are both acceptable and should return 10.



                I would use Vlad's solution but sub in this function instead of indexOf === -1 to check if a pair exists already:



                function checkPairExists(value,position,pairsArray)
                for(var i = 0; i < pairsArray.length; i++)
                if (pairsArray[i].value === value && pairsArray[i].position === position)
                return true;


                return false;






                share|improve this answer











                $endgroup$



                Vlad Z answer is correct but freecodecamp has weird wording on this problem. I used a similar answer but was failing on this test:



                expect(pairwise([0, 0, 0, 0, 1, 1], 1)).to.equal(10);


                My problem and the problem with Vlad Zs solution is that 0,1 -> indexes (0 and 4) and 0,1 indexes(1 and 5) are both acceptable and should return 10.



                I would use Vlad's solution but sub in this function instead of indexOf === -1 to check if a pair exists already:



                function checkPairExists(value,position,pairsArray)
                for(var i = 0; i < pairsArray.length; i++)
                if (pairsArray[i].value === value && pairsArray[i].position === position)
                return true;


                return false;







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 3 '15 at 15:10









                Malachi

                25.6k774176




                25.6k774176










                answered Aug 3 '15 at 15:00









                Frank TreadwellFrank Treadwell

                1211




                1211





















                    2












                    $begingroup$

                    This function implementation uses the "reduce" method to get the sum of the indexes and it fullfills all Free Code Camp tests.



                    function pairwise(arr, arg) 
                    return arr.reduce((sum, value1, index1) =>
                    arr.slice(index1 + 1).forEach((value2, index2) =>
                    if (arr[index1] + arr[index1 + 1 + index2] === arg)
                    arr[index1] = arr[index1 + 1 + index2] = NaN;
                    sum += index1 + index1 + 1 + index2;

                    );
                    return sum;
                    , 0);






                    share|improve this answer









                    $endgroup$

















                      2












                      $begingroup$

                      This function implementation uses the "reduce" method to get the sum of the indexes and it fullfills all Free Code Camp tests.



                      function pairwise(arr, arg) 
                      return arr.reduce((sum, value1, index1) =>
                      arr.slice(index1 + 1).forEach((value2, index2) =>
                      if (arr[index1] + arr[index1 + 1 + index2] === arg)
                      arr[index1] = arr[index1 + 1 + index2] = NaN;
                      sum += index1 + index1 + 1 + index2;

                      );
                      return sum;
                      , 0);






                      share|improve this answer









                      $endgroup$















                        2












                        2








                        2





                        $begingroup$

                        This function implementation uses the "reduce" method to get the sum of the indexes and it fullfills all Free Code Camp tests.



                        function pairwise(arr, arg) 
                        return arr.reduce((sum, value1, index1) =>
                        arr.slice(index1 + 1).forEach((value2, index2) =>
                        if (arr[index1] + arr[index1 + 1 + index2] === arg)
                        arr[index1] = arr[index1 + 1 + index2] = NaN;
                        sum += index1 + index1 + 1 + index2;

                        );
                        return sum;
                        , 0);






                        share|improve this answer









                        $endgroup$



                        This function implementation uses the "reduce" method to get the sum of the indexes and it fullfills all Free Code Camp tests.



                        function pairwise(arr, arg) 
                        return arr.reduce((sum, value1, index1) =>
                        arr.slice(index1 + 1).forEach((value2, index2) =>
                        if (arr[index1] + arr[index1 + 1 + index2] === arg)
                        arr[index1] = arr[index1 + 1 + index2] = NaN;
                        sum += index1 + index1 + 1 + index2;

                        );
                        return sum;
                        , 0);







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jul 13 '16 at 10:19









                        Paulo BotoPaulo Boto

                        212




                        212





















                            2












                            $begingroup$

                            I came to the same conclusion as Piotr, but with a slight improvement - dropping one more un-necessary check. See comments in code below:



                            function pairwise(arr, arg) 
                            var sum = 0;

                            for (var i=0; i < arr.length - 1; i++)
                            for (var j=i+1; j < arr.length; j++)
                            //No need to check for less than arg, used elements are naturally eliminated
                            if (arr[i] + arr[j] === arg)
                            sum += i + j;
                            arr[i] = arr[j] = arg + 1; //Set the used elements to higher than arg e.g. arg + 1




                            return sum;


                            pairwise([1,4,2,3,0,5], 7);





                            share|improve this answer









                            $endgroup$

















                              2












                              $begingroup$

                              I came to the same conclusion as Piotr, but with a slight improvement - dropping one more un-necessary check. See comments in code below:



                              function pairwise(arr, arg) 
                              var sum = 0;

                              for (var i=0; i < arr.length - 1; i++)
                              for (var j=i+1; j < arr.length; j++)
                              //No need to check for less than arg, used elements are naturally eliminated
                              if (arr[i] + arr[j] === arg)
                              sum += i + j;
                              arr[i] = arr[j] = arg + 1; //Set the used elements to higher than arg e.g. arg + 1




                              return sum;


                              pairwise([1,4,2,3,0,5], 7);





                              share|improve this answer









                              $endgroup$















                                2












                                2








                                2





                                $begingroup$

                                I came to the same conclusion as Piotr, but with a slight improvement - dropping one more un-necessary check. See comments in code below:



                                function pairwise(arr, arg) 
                                var sum = 0;

                                for (var i=0; i < arr.length - 1; i++)
                                for (var j=i+1; j < arr.length; j++)
                                //No need to check for less than arg, used elements are naturally eliminated
                                if (arr[i] + arr[j] === arg)
                                sum += i + j;
                                arr[i] = arr[j] = arg + 1; //Set the used elements to higher than arg e.g. arg + 1




                                return sum;


                                pairwise([1,4,2,3,0,5], 7);





                                share|improve this answer









                                $endgroup$



                                I came to the same conclusion as Piotr, but with a slight improvement - dropping one more un-necessary check. See comments in code below:



                                function pairwise(arr, arg) 
                                var sum = 0;

                                for (var i=0; i < arr.length - 1; i++)
                                for (var j=i+1; j < arr.length; j++)
                                //No need to check for less than arg, used elements are naturally eliminated
                                if (arr[i] + arr[j] === arg)
                                sum += i + j;
                                arr[i] = arr[j] = arg + 1; //Set the used elements to higher than arg e.g. arg + 1




                                return sum;


                                pairwise([1,4,2,3,0,5], 7);






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Oct 31 '16 at 14:58









                                balachbalach

                                211




                                211





















                                    1












                                    $begingroup$

                                    The requirements are broken down into:



                                    • Return the sum of all indices of elements of 'arr' that can be paired with one other element to form a sum that equals the value in the second argument 'arg'.

                                    • If multiple sums are possible, return the smallest sum. Once an element has been used

                                    • Once an element has been used, it cannot be reused to pair with another.

                                    The first bullet point is easy enough to understand. We find pairs that sum up to the total, and sum up the indices.



                                    However, your example contradicts the second bullet point. If multiple sums are found, it should return the smallest. 4 and 3 are 1 and 3 which results to 4. 2 and 5 are 2 and 5 which results to 7. The result should be 4 in the first example.



                                    So here's my take on it






                                    function pairwise(arr, total) 
                                    // For each item in the array
                                    var sums = arr.reduce(function (indexSum, firstNumber, firstIndex)
                                    // Collect the pair's index which causes the numbers to sum to total
                                    var secondIndices = arr.slice(firstIndex + 1).reduce(function (secondIndices, secondNumber, i)
                                    if (firstNumber + secondNumber === total) secondIndices.push(firstIndex + i + 1);
                                    return secondIndices;
                                    , []);
                                    // Add to our collection the sum this iteration's index and
                                    // the pair indices
                                    return indexSum.concat(secondIndices.map(function (secondIndex)
                                    return secondIndex + firstIndex
                                    ));
                                    , []);
                                    // In all the items, find the smallest sum
                                    return Math.min.apply(null, sums);


                                    console.log(pairwise([1, 4, 2, 3, 0, 5], 7));
                                    console.log(pairwise([1, 3, 2, 4], 4));





                                    Regarding bullet point 3, I would care less if a number was reused, like in the case of 6 in [4, 4, 2] or say [4, 2, 9, 9, 4] because any number that's going to pair with it after the first established pair will have a higher index sum anyways.






                                    share|improve this answer









                                    $endgroup$












                                    • $begingroup$
                                      Thanks for the great reply, the way I read the second requirement - returning smallest sum, was that if the target could be reached by two calculations sharing one number then we should use the calculation whose sum of indices is smallest. For example: pairwise([0,1,1], 1) should return 1, even though it is possible to use the last number in the array with the 0 to get an answer of 2, we should use the smallest index sum. Thanks again though and you managed to use array.reduce()! I would never have gotten that.
                                      $endgroup$
                                      – John Behan
                                      Jul 31 '15 at 6:40
















                                    1












                                    $begingroup$

                                    The requirements are broken down into:



                                    • Return the sum of all indices of elements of 'arr' that can be paired with one other element to form a sum that equals the value in the second argument 'arg'.

                                    • If multiple sums are possible, return the smallest sum. Once an element has been used

                                    • Once an element has been used, it cannot be reused to pair with another.

                                    The first bullet point is easy enough to understand. We find pairs that sum up to the total, and sum up the indices.



                                    However, your example contradicts the second bullet point. If multiple sums are found, it should return the smallest. 4 and 3 are 1 and 3 which results to 4. 2 and 5 are 2 and 5 which results to 7. The result should be 4 in the first example.



                                    So here's my take on it






                                    function pairwise(arr, total) 
                                    // For each item in the array
                                    var sums = arr.reduce(function (indexSum, firstNumber, firstIndex)
                                    // Collect the pair's index which causes the numbers to sum to total
                                    var secondIndices = arr.slice(firstIndex + 1).reduce(function (secondIndices, secondNumber, i)
                                    if (firstNumber + secondNumber === total) secondIndices.push(firstIndex + i + 1);
                                    return secondIndices;
                                    , []);
                                    // Add to our collection the sum this iteration's index and
                                    // the pair indices
                                    return indexSum.concat(secondIndices.map(function (secondIndex)
                                    return secondIndex + firstIndex
                                    ));
                                    , []);
                                    // In all the items, find the smallest sum
                                    return Math.min.apply(null, sums);


                                    console.log(pairwise([1, 4, 2, 3, 0, 5], 7));
                                    console.log(pairwise([1, 3, 2, 4], 4));





                                    Regarding bullet point 3, I would care less if a number was reused, like in the case of 6 in [4, 4, 2] or say [4, 2, 9, 9, 4] because any number that's going to pair with it after the first established pair will have a higher index sum anyways.






                                    share|improve this answer









                                    $endgroup$












                                    • $begingroup$
                                      Thanks for the great reply, the way I read the second requirement - returning smallest sum, was that if the target could be reached by two calculations sharing one number then we should use the calculation whose sum of indices is smallest. For example: pairwise([0,1,1], 1) should return 1, even though it is possible to use the last number in the array with the 0 to get an answer of 2, we should use the smallest index sum. Thanks again though and you managed to use array.reduce()! I would never have gotten that.
                                      $endgroup$
                                      – John Behan
                                      Jul 31 '15 at 6:40














                                    1












                                    1








                                    1





                                    $begingroup$

                                    The requirements are broken down into:



                                    • Return the sum of all indices of elements of 'arr' that can be paired with one other element to form a sum that equals the value in the second argument 'arg'.

                                    • If multiple sums are possible, return the smallest sum. Once an element has been used

                                    • Once an element has been used, it cannot be reused to pair with another.

                                    The first bullet point is easy enough to understand. We find pairs that sum up to the total, and sum up the indices.



                                    However, your example contradicts the second bullet point. If multiple sums are found, it should return the smallest. 4 and 3 are 1 and 3 which results to 4. 2 and 5 are 2 and 5 which results to 7. The result should be 4 in the first example.



                                    So here's my take on it






                                    function pairwise(arr, total) 
                                    // For each item in the array
                                    var sums = arr.reduce(function (indexSum, firstNumber, firstIndex)
                                    // Collect the pair's index which causes the numbers to sum to total
                                    var secondIndices = arr.slice(firstIndex + 1).reduce(function (secondIndices, secondNumber, i)
                                    if (firstNumber + secondNumber === total) secondIndices.push(firstIndex + i + 1);
                                    return secondIndices;
                                    , []);
                                    // Add to our collection the sum this iteration's index and
                                    // the pair indices
                                    return indexSum.concat(secondIndices.map(function (secondIndex)
                                    return secondIndex + firstIndex
                                    ));
                                    , []);
                                    // In all the items, find the smallest sum
                                    return Math.min.apply(null, sums);


                                    console.log(pairwise([1, 4, 2, 3, 0, 5], 7));
                                    console.log(pairwise([1, 3, 2, 4], 4));





                                    Regarding bullet point 3, I would care less if a number was reused, like in the case of 6 in [4, 4, 2] or say [4, 2, 9, 9, 4] because any number that's going to pair with it after the first established pair will have a higher index sum anyways.






                                    share|improve this answer









                                    $endgroup$



                                    The requirements are broken down into:



                                    • Return the sum of all indices of elements of 'arr' that can be paired with one other element to form a sum that equals the value in the second argument 'arg'.

                                    • If multiple sums are possible, return the smallest sum. Once an element has been used

                                    • Once an element has been used, it cannot be reused to pair with another.

                                    The first bullet point is easy enough to understand. We find pairs that sum up to the total, and sum up the indices.



                                    However, your example contradicts the second bullet point. If multiple sums are found, it should return the smallest. 4 and 3 are 1 and 3 which results to 4. 2 and 5 are 2 and 5 which results to 7. The result should be 4 in the first example.



                                    So here's my take on it






                                    function pairwise(arr, total) 
                                    // For each item in the array
                                    var sums = arr.reduce(function (indexSum, firstNumber, firstIndex)
                                    // Collect the pair's index which causes the numbers to sum to total
                                    var secondIndices = arr.slice(firstIndex + 1).reduce(function (secondIndices, secondNumber, i)
                                    if (firstNumber + secondNumber === total) secondIndices.push(firstIndex + i + 1);
                                    return secondIndices;
                                    , []);
                                    // Add to our collection the sum this iteration's index and
                                    // the pair indices
                                    return indexSum.concat(secondIndices.map(function (secondIndex)
                                    return secondIndex + firstIndex
                                    ));
                                    , []);
                                    // In all the items, find the smallest sum
                                    return Math.min.apply(null, sums);


                                    console.log(pairwise([1, 4, 2, 3, 0, 5], 7));
                                    console.log(pairwise([1, 3, 2, 4], 4));





                                    Regarding bullet point 3, I would care less if a number was reused, like in the case of 6 in [4, 4, 2] or say [4, 2, 9, 9, 4] because any number that's going to pair with it after the first established pair will have a higher index sum anyways.






                                    function pairwise(arr, total) 
                                    // For each item in the array
                                    var sums = arr.reduce(function (indexSum, firstNumber, firstIndex)
                                    // Collect the pair's index which causes the numbers to sum to total
                                    var secondIndices = arr.slice(firstIndex + 1).reduce(function (secondIndices, secondNumber, i)
                                    if (firstNumber + secondNumber === total) secondIndices.push(firstIndex + i + 1);
                                    return secondIndices;
                                    , []);
                                    // Add to our collection the sum this iteration's index and
                                    // the pair indices
                                    return indexSum.concat(secondIndices.map(function (secondIndex)
                                    return secondIndex + firstIndex
                                    ));
                                    , []);
                                    // In all the items, find the smallest sum
                                    return Math.min.apply(null, sums);


                                    console.log(pairwise([1, 4, 2, 3, 0, 5], 7));
                                    console.log(pairwise([1, 3, 2, 4], 4));





                                    function pairwise(arr, total) 
                                    // For each item in the array
                                    var sums = arr.reduce(function (indexSum, firstNumber, firstIndex)
                                    // Collect the pair's index which causes the numbers to sum to total
                                    var secondIndices = arr.slice(firstIndex + 1).reduce(function (secondIndices, secondNumber, i)
                                    if (firstNumber + secondNumber === total) secondIndices.push(firstIndex + i + 1);
                                    return secondIndices;
                                    , []);
                                    // Add to our collection the sum this iteration's index and
                                    // the pair indices
                                    return indexSum.concat(secondIndices.map(function (secondIndex)
                                    return secondIndex + firstIndex
                                    ));
                                    , []);
                                    // In all the items, find the smallest sum
                                    return Math.min.apply(null, sums);


                                    console.log(pairwise([1, 4, 2, 3, 0, 5], 7));
                                    console.log(pairwise([1, 3, 2, 4], 4));






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jul 30 '15 at 17:17









                                    JosephJoseph

                                    22.8k21935




                                    22.8k21935











                                    • $begingroup$
                                      Thanks for the great reply, the way I read the second requirement - returning smallest sum, was that if the target could be reached by two calculations sharing one number then we should use the calculation whose sum of indices is smallest. For example: pairwise([0,1,1], 1) should return 1, even though it is possible to use the last number in the array with the 0 to get an answer of 2, we should use the smallest index sum. Thanks again though and you managed to use array.reduce()! I would never have gotten that.
                                      $endgroup$
                                      – John Behan
                                      Jul 31 '15 at 6:40

















                                    • $begingroup$
                                      Thanks for the great reply, the way I read the second requirement - returning smallest sum, was that if the target could be reached by two calculations sharing one number then we should use the calculation whose sum of indices is smallest. For example: pairwise([0,1,1], 1) should return 1, even though it is possible to use the last number in the array with the 0 to get an answer of 2, we should use the smallest index sum. Thanks again though and you managed to use array.reduce()! I would never have gotten that.
                                      $endgroup$
                                      – John Behan
                                      Jul 31 '15 at 6:40
















                                    $begingroup$
                                    Thanks for the great reply, the way I read the second requirement - returning smallest sum, was that if the target could be reached by two calculations sharing one number then we should use the calculation whose sum of indices is smallest. For example: pairwise([0,1,1], 1) should return 1, even though it is possible to use the last number in the array with the 0 to get an answer of 2, we should use the smallest index sum. Thanks again though and you managed to use array.reduce()! I would never have gotten that.
                                    $endgroup$
                                    – John Behan
                                    Jul 31 '15 at 6:40





                                    $begingroup$
                                    Thanks for the great reply, the way I read the second requirement - returning smallest sum, was that if the target could be reached by two calculations sharing one number then we should use the calculation whose sum of indices is smallest. For example: pairwise([0,1,1], 1) should return 1, even though it is possible to use the last number in the array with the 0 to get an answer of 2, we should use the smallest index sum. Thanks again though and you managed to use array.reduce()! I would never have gotten that.
                                    $endgroup$
                                    – John Behan
                                    Jul 31 '15 at 6:40












                                    1












                                    $begingroup$

                                    The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
                                    http://codepen.io/PiotrBerebecki/pen/RRGaBZ.



                                    function pairwise(arr, arg) 
                                    var sum = 0;
                                    for (var i=0; i<arr.length-1; i++)
                                    for (var j=i+1; j<arr.length; j++)
                                    if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg)
                                    sum += i+j;
                                    arr[i] = arr[j] = NaN;



                                    return sum;


                                    console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6


                                    Under the hood:



                                    1. Start looping from the element with index (i) = 0.

                                    2. Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.

                                    3. If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.

                                    4. If the pair has been found then change their values to NaN to avoid further checks and duplication.





                                    share|improve this answer











                                    $endgroup$

















                                      1












                                      $begingroup$

                                      The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
                                      http://codepen.io/PiotrBerebecki/pen/RRGaBZ.



                                      function pairwise(arr, arg) 
                                      var sum = 0;
                                      for (var i=0; i<arr.length-1; i++)
                                      for (var j=i+1; j<arr.length; j++)
                                      if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg)
                                      sum += i+j;
                                      arr[i] = arr[j] = NaN;



                                      return sum;


                                      console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6


                                      Under the hood:



                                      1. Start looping from the element with index (i) = 0.

                                      2. Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.

                                      3. If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.

                                      4. If the pair has been found then change their values to NaN to avoid further checks and duplication.





                                      share|improve this answer











                                      $endgroup$















                                        1












                                        1








                                        1





                                        $begingroup$

                                        The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
                                        http://codepen.io/PiotrBerebecki/pen/RRGaBZ.



                                        function pairwise(arr, arg) 
                                        var sum = 0;
                                        for (var i=0; i<arr.length-1; i++)
                                        for (var j=i+1; j<arr.length; j++)
                                        if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg)
                                        sum += i+j;
                                        arr[i] = arr[j] = NaN;



                                        return sum;


                                        console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6


                                        Under the hood:



                                        1. Start looping from the element with index (i) = 0.

                                        2. Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.

                                        3. If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.

                                        4. If the pair has been found then change their values to NaN to avoid further checks and duplication.





                                        share|improve this answer











                                        $endgroup$



                                        The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
                                        http://codepen.io/PiotrBerebecki/pen/RRGaBZ.



                                        function pairwise(arr, arg) 
                                        var sum = 0;
                                        for (var i=0; i<arr.length-1; i++)
                                        for (var j=i+1; j<arr.length; j++)
                                        if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg)
                                        sum += i+j;
                                        arr[i] = arr[j] = NaN;



                                        return sum;


                                        console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6


                                        Under the hood:



                                        1. Start looping from the element with index (i) = 0.

                                        2. Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.

                                        3. If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.

                                        4. If the pair has been found then change their values to NaN to avoid further checks and duplication.






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jun 18 '16 at 13:32









                                        rolfl

                                        91.2k13193397




                                        91.2k13193397










                                        answered Jun 18 '16 at 11:02









                                        Piotr BerebeckiPiotr Berebecki

                                        1113




                                        1113





















                                            0












                                            $begingroup$

                                            Old forum but wanted to contribute an ES6 solution



                                             function pairwise(arr, arg) 
                                            let sum=0;

                                            // ES6
                                            for(let i in arr)
                                            for(let j in arr)
                                            if(i!=j)
                                            if ((arr[i]+arr[j]) === arg)
                                            sum += (Number(i)+Number(j));
                                            arr[i] = arr[j] = arg+1;




                                            return sum;


                                            pairwise([1, 4, 2, 3, 0, 5], 7)





                                            share|improve this answer








                                            New contributor




                                            Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                            Check out our Code of Conduct.






                                            $endgroup$

















                                              0












                                              $begingroup$

                                              Old forum but wanted to contribute an ES6 solution



                                               function pairwise(arr, arg) 
                                              let sum=0;

                                              // ES6
                                              for(let i in arr)
                                              for(let j in arr)
                                              if(i!=j)
                                              if ((arr[i]+arr[j]) === arg)
                                              sum += (Number(i)+Number(j));
                                              arr[i] = arr[j] = arg+1;




                                              return sum;


                                              pairwise([1, 4, 2, 3, 0, 5], 7)





                                              share|improve this answer








                                              New contributor




                                              Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                              Check out our Code of Conduct.






                                              $endgroup$















                                                0












                                                0








                                                0





                                                $begingroup$

                                                Old forum but wanted to contribute an ES6 solution



                                                 function pairwise(arr, arg) 
                                                let sum=0;

                                                // ES6
                                                for(let i in arr)
                                                for(let j in arr)
                                                if(i!=j)
                                                if ((arr[i]+arr[j]) === arg)
                                                sum += (Number(i)+Number(j));
                                                arr[i] = arr[j] = arg+1;




                                                return sum;


                                                pairwise([1, 4, 2, 3, 0, 5], 7)





                                                share|improve this answer








                                                New contributor




                                                Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.






                                                $endgroup$



                                                Old forum but wanted to contribute an ES6 solution



                                                 function pairwise(arr, arg) 
                                                let sum=0;

                                                // ES6
                                                for(let i in arr)
                                                for(let j in arr)
                                                if(i!=j)
                                                if ((arr[i]+arr[j]) === arg)
                                                sum += (Number(i)+Number(j));
                                                arr[i] = arr[j] = arg+1;




                                                return sum;


                                                pairwise([1, 4, 2, 3, 0, 5], 7)






                                                share|improve this answer








                                                New contributor




                                                Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.









                                                share|improve this answer



                                                share|improve this answer






                                                New contributor




                                                Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.









                                                answered 21 mins ago









                                                RobertRobert

                                                1




                                                1




                                                New contributor




                                                Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.





                                                New contributor





                                                Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.






                                                Robert is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                Check out our Code of Conduct.



























                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Code Review Stack Exchange!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    Use MathJax to format equations. MathJax reference.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f98448%2ffree-code-camp-pairwise%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

                                                    Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

                                                    चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि