yunjae123 yunjae123 - 1 month ago 6
Javascript Question

divisibleByThreePairSum, I get pair repeats

i'm just beginning to learn javascript and this is my first question on stackoverflow, so feel free to criticize me if i'm approaching this the wrong way.

var divisibleByThreePairSum = function(array) {
var pairs = [];

for (var i = 0; i < array.length; i++) {
for (var j = i++; j < array.length; j++) {
var sum = array[i] + array[j];

if (sum % 3 === 0) {
pairs.push([i, j]);
}
}
}

return pairs;
}
console.log(divisibleByThreePairSum([3,1,0,2,1,3,2,0]));


This gives me the answer;

[ [ 1, 3 ], [ 1, 6 ], [ 3, 4 ], [ 5, 5 ], [ 5, 7 ], [ 7, 7 ] ]
[Finished in 0.2s]


For the second "for" loop, I formatted it like so, (j = i++) as to avoid repeats like [1, 3], [3, 1], but I can't seem to get rid of getting pairs like [5, 5], and [7, 7]. Is there any possible ways to format the code differently so that this doesn't happen? Again, I apologize if this was asked improperly; i'll definitely be using this site more often so please let me know if i'm doing anything wrong "question format" wise, Thanks!

Answer

Issue is j = i++. This will assign value of i to j and then increment value of i. This will also result in skipping of alternate values of i as it is incremented twice.

for(var i = 0; i< 5; i++){
  for(var j = i++; j< 5; j++){
    console.log(i,j)
  }
}

You should rather use j=i+1. This will sent next value and will not increment value of i

var divisibleByThreePairSum = function(array) {
  var pairs = [];

  for (var i = 0; i < array.length; i++) {
    for (var j = i+1; j < array.length; j++) {
      var sum = array[i] + array[j];

      if (sum % 3 === 0) {
        pairs.push([i, j]);
      }
    }
  }

  return pairs;
}

console.log(divisibleByThreePairSum([3, 1, 0, 2, 1, 3, 2, 0]));