[JS Practice] Difference of 2 (相差2)

Title :

Difference of 2

Description:

The objective is to obtain the various sets of integers that have a difference of 2 from a given array of integers. The result array should be sorted in ascending order of values.

So for example for the array of integers

[1,2,3,4] should return [[1,3],[2,4]]

[4,1,2,3] should also return [[1,3],[2,4]]

[1,23,3,4,7] should return [[1,3]]

Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.

My solution :

function twosDifference(input){
  var arrTmp = input.sort().reverse(); // Descending
  var arrRet = [],
      len = input.length;

   for( i=0; i<len; i++) {
     for(j=0; j<len; j++) {
       if(arrTmp[i] - arrTmp[j] == 2) {
          var arrTab = [arrTmp[j], arrTmp[i]];
          arrRet.push(arrTab);
       }
    }
  }

  // Sort array
  arrRet = arrRet.sort(function(a, b){
     return a[0] - b[0];
  });
   return arrRet;
}

Best solution :

function twosDifference(input){
  return input
   .sort(function(a, b){
     return a - b
   })
   .filter(function(a){
     return input.indexOf(a+2) != -1
   })
   .map(function(a){
     return [a, a+2]
   })
}

 

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s