freeCodeCamp / wiki

freeCodeCamp's deprecated wiki articles
http://www.freecodecamp.com/wiki
281 stars 308 forks source link

Add advanced solution to 'Pairwise' challenge solution #1217

Closed ortonomy closed 8 years ago

ortonomy commented 8 years ago

Pairwise

https://www.freecodecamp.com/wiki/en/algorithm-pairwise/

This challenge is missing an 'advanced' solution

I believe that my solution for this challenge represents a suitably more 'advanced solution' for this challenge, including avoiding imperative for loops and using declarative statements using native array functions

I don't want to clone the whole wiki locally and make a pull request, so how do I contribute / add this to the solution?

Your Code

This solution uses only native array operations and avoids for loops.

function pairwise(arr, arg) {
  // search array for elements that when paired, equal the second argument, then sum their indices

  return arr.reduce( function (a,b,index){ // use native reduce to collect running total of summed indices
      var search = arg - b; // get difference of current item so we know what value will sum to arg

      // check if search value in rest of the array, but also make sure it doesn't match current search index
      if ( arr.indexOf(search) != -1 && arr.indexOf(search) != index ){ 
         var total = index + arr.indexOf(search);  // if found, add to the runnning total
         arr.splice(index,1,NaN); // remove current index from the array
         arr.splice(arr.indexOf(search),1,NaN); // remove the other matched element from the array
         return a + total; //return the running total back to reduce for next item
      }
      return a; // simply return previous total if no operations needed
  },0);

}

Code explanation: See comments in code This code takes advantage of the fact that the native Array.prototype.indexOf() method will return the lowest index of the value it finds, a requirement of the challenge. Given that you start with the first item in the array (automatically the lowest of it's value), you're guaranteed to always find the lowest pairs, before removing them from the search space.

Username to add:

@geligelu

alayek commented 8 years ago

Alright. Please raise a PR.

ortonomy commented 8 years ago

Squash commit 25bed7feb5742774f3d7d0fb75e9d322f71f3062 - incorrect message.