Pinncik
Pinncik

Reputation: 321

How to check if 2D array has three same values in a row

I’m trying to find out how is it possible to check if 2D array contains 3 same values in a row. This 2D array will be generated by user, so function for checking must be dynamic.

For example let's say user types in 4x4. Result will be this

  let arr=[
    [" "," "," "," "],
    [" "," "," "," "],
    [" "," "," "," "],
    [" "," "," "," "]
  ]

Let me add some values to that array

  let arr=[
    [" "," ","x","x"],
    ["x","x","x"," "],
    [" "," "," "," "],
    [" "," "," "," "]
  ]

I've tried to solve this with this function, but yesterday I've noticed it doesn't for properly.

  function checkArray(arr){
    for(let i=0;i<arr.length;i++){
      let count = 0;
      for(let j=0;j<arr[i].length;j++){
        if(arr[i][j] === 'x'){
          count++;
        }

        if(count === 3 ){
          console.log('x wins')
        }
      }
    }
  }
  
  console.log(checkArray(arr)) //count will be 3 and console.logs 'x wins'.

At this moment I thought everything is working fine until I've tried to fill the array like this. As you can see there are not three X's in a row(I mean they don't go like this - x,x,x), and there is one blank space between them.

  let arr=[
    [" "," ","x","x"],
    ["x","x"," ","x"],
    [" "," "," "," "],
    [" "," "," "," "]
  ]

So condition shouldn't be fulfilled and function should not console.log('w wins'). But it does. My approach for this problem is working for whole row ,not only if there are 3 in a row (x,x,x).

I hope I've explained it clearly. Thanks for you advices.

Upvotes: 1

Views: 893

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

You need to reset the count if you do not get an 'x'.

function checkArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    let count = 0;
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] === 'x') {
        count++;
        if (count === 3) {                    // place check after incrementing
          console.log('x wins')
          return true;
        }
      } else {
        count = 0;                            // reset
      }
    }
  }
  return false;
}

let arr = [
  [" ", " ", "x", "x"],
  ["x", "x", " ", "x"],
  [" ", " ", " ", " "],
  [" ", " ", " ", " "]
]

console.log(checkArray(arr));

Upvotes: 1

Related Questions