0

I'm trying to figure out how to find 3 or matching consecutive values in a 2D array. I think I have the horizontal and vertical matching figured out but how would I match if the same value was present in two different rows like this following list array (myArray):

| 1 | 2 | 2 | 0 |
| - | 2 | 0 | 1 |
| 1 | - | 0 | 1 |

In this particular 2D array, myArray[0][1], myArray[0][2], and myArray[1][1] all match the value of 2.

Here is the JavaScript I have to find matches for both horizontal and vertical matches:

for (i in myArray) {
    for (j in myArray[i]) {
        if (myArray[i][j] == myArray[i][j - 1] && myArray[i][j - 1] == myArray[i][j - 2] && myArray[i][j] != "-") {
            // do something
        }
        if (i > 1) {
            if (myArray[i][j] == myArray[i - 1][j] && myArray[i - 1][j] == myArray[i - 2][j] && myArray[i][j] != "-") {
                // do something
            }                           
        }
    }
}

Am I on the right track here? I'm guessing I can mix the two if statements to find the matches but I'm at a bit of a lost as to how.

Thanks!

Szabolcs Páll
  • 1,402
  • 6
  • 25
  • 31
Jawa
  • 99
  • 2
  • 12
  • 1. Use triple equal signs (===) 2. What exactly are you asking? Do you need to tell if there is a match both horizontally and vertically? Give an example of the desired output – DUUUDE123 Jun 07 '15 at 23:06

1 Answers1

0

Test for the cross around each element.

for (var y=0, yLen=myArray.length; y<yLen; y++){
  for (var x=0, xLen=myArray[y].length; x<xLen; x++){
      var matches = 0,
          testing = myArray[y][x];
      // test left
      if (x>0 && myArray[y][x-1] === testing) matches++;
      // test right
      if ((x<myArray[y].length-1) && myArray[y][x+1] === testing) matches++; 
      // test above
      if (y>0 && myArray[y-1][x] === testing) matches++; 
      // test below
      if ((y<myArray.length-1) && myArray[y+1][x] === testing) matches++; 

      if (matches>=2){
         console.log(y,x,' is the central or corner element of a 3-or-more group');
      }
  }
}

Keep in mind that this will only return true for the central element of group (either the center element in 3 horizontal or 3 vertical, or the corner element when the group is in both directions)


Also it is a bad idea to use for .. in for arrays for the reasons described in Why is using "for...in" with array iteration a bad idea?

Community
  • 1
  • 1
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317