0

I tried to create a 2D array and place four "X" in diagonal and created a double loop for detecting and counting the number of Xs ,it works but it doesnt do the job properly what it really does is that it counts the number of Xs in every row, my question how can i make it count just the Xs on diagonal ?

    var creatematrix = function (nbRang, nbColumn) {
        var result = Array(nbRang);
        for (var i=0; i<nbRang; i++) {
            result[i] = Array(nbColumn);
        }
        return result;
    };

    var m = creatematrix(6, 7);

for example if i did this

      m[4][1] = "X";
      m[3][2] = "X";
      m[2][3] = "X";
      m[1][4] = "X";

      m[5][3] = "O";
      m[3][3] = "O";
      m[4][3] = "O";
      m[2][4] = "O";

or this the result is the same

    m[1][1] = "X";
    m[2][1] = "X";
    m[3][1] = "X";
    m[4][1] = "X";



    m[5][3] = "O";
    m[3][3] = "O";
    m[4][3] = "O";
    m[2][4] = "O";

Here is what I have:

   var sumX = 0;
   for(var k = 5; k >= 0  ; k--){
       if(sumX == 4){
           alert("player 1 won");
       }
       for(var i = 0 ; i<= 6; i++){
           if(m[k][i]== "X" ){
               sumX += 1;
               break;
           }
           if(m[k][i]== "O" ){
              sumX = 0;         
           }
       }
   }    
0

1 Answer 1

1
function getCount(m){
    var count =0;
    for(var i=0; i<m.length; i++)
    {
      if(m[i][m.length-i-1] === "X")
      {
         count++;
      }
    }

    return count;
}

That will just go down the diagonal and check each value.

You can also do a shorter (but less readable) version with

function getCount(m){
    return m.reduce(function(prev,current,index,arr){ 
      return prev + current[arr.length-index-1];},0);
}

JSFiddle

Sign up to request clarification or add additional context in comments.

6 Comments

@nooby102030 define "doesn't work" what doesn't it do that you expect?
your code doesnt count the X on the diagonal i tried it and it doesn't count them
I had a typo and it said counter instead of count. Thats fixed, and there's a working example here: jsfiddle.net/LknbJ
@nooby102030 which diagonal are you trying to count on? This code counts on the bottom left to top right diagonal, since that seemed like what you were trying for with your code. Is that what you want?
i saw the counter++ and i corrected it before you mention it but still doesnt do what i expect
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.