0

I have been struggling with this for a while. Hopefully someone can help. Here goes. I have 2 dimensional array that is initialized in a nested for loop. If the dimensions of the array mod (%) 2 is even (d%2 == 0), I want to swap the element 2 and element 1 in the array matrix with one another.

Another idea I am struggling with is this, instead of perform a swap I could just simply explicit assign the 1 and 2 to the index of the array inside the for loop.

Here is the code I have so far.. I appreciate any inputs that will assist me to arriving at the right solution..

if (d % 2 == 0)
{        
    for (row_i = 0; row_i < d; row_i++)//loops through rows
    {
        for(col_j = 0; col_j < d; col_j++) //loops through column
        {
            board[row_i][col_j] = multi_dim--;
            if(board[row_i][col_j] == 2 && board[row_i][col_j] == 1)
            {
                int hold = board[d][d -2];
                board[d][d - 2] = board[d][d - 1];
                board[d][d - 1] = hold;
            }
            printf(" %2d ", board[row_i][col_j]);
        }
        printf("\n");  
    }
}
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • I don't quite get the logic you're describing. Is this to rotate a matrix? Check this question: http://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array – DarthNoodles Feb 25 '16 at 22:16

1 Answers1

1
if(board[row_i][col_j] == 2 && board[row_i][col_j] == 1)

This test is always false. You're asking the same variable 'board[row_i][col_j]' to be 2 and 1 at the same time.

DarthNoodles
  • 370
  • 3
  • 11
  • I see. Would having a nested if statement be a better option.. if(board[row_i][col_j] == 2) { if(board[row_i][col_j] == 2) { int hold = board[d][d -2]; board[d][d - 2] = board[d][d - 1]; board[d][d - 1] = hold; } } – Barinuadum Emmanuel Bariyiga Feb 25 '16 at 01:19
  • To be honest I don't quite understand the problem you're trying to solve. I just noticed the logic problem and pointed it out. Your 'better' option is no different. Nesting if's is the same as an '&&' since it only gets to the inner code if both conditions are true. – DarthNoodles Feb 25 '16 at 22:12
  • Oh ok.. So the for loops are supposed to iterate through and initialize the array boards[][] with the values of multi_dim, which is initialized (d*d) - 1. There is a condition is the that check if d%2 == 0. if that is true, I want to swap array index that is initialize with the value 2 with the array index that is initialized with the value 1. That is what I am having trouble with – Barinuadum Emmanuel Bariyiga Feb 25 '16 at 23:35
  • @Barinuadum Emmanuel Bariyiga - Your phrase _to swap array index_ is unintelligible. Add the desired contents of `board` for d = 2 to your question as an example. – Armali Apr 15 '16 at 11:57