0

I noticed that my in my init function, that the '1' and '2' variables weren't switching correctly.

After playing around with my code, I have noticed that this works:

void init(void)
{
    // initilizes array

    int total = d * d; 

    for (int row = 0; row < d; row++)
    {
        for (int col = 0; col < d; col ++)
        {
            board[row][col] = --total;
        }
    }

    // Swap 2 and 1 if even number of spaces

    if (((d*d)-1) % 2 != 0)
    {
        int temp = board[d-1][d-2];
        board[d-1][d-2] = board[d-1][d-3];
        board[d-1][d-3] = temp;
    }  

But THIS doesn't.

    if ((total-1) % 2 != 0)
    {
        int temp = board[d-1][d-2];
        board[d-1][d-2] = board[d-1][d-3];
        board[d-1][d-3] = temp;
    }

In both functions, I have declared that 'total == d * d'

I know this is done correctly because I have already swapped initalized the array. Can you please tell me why? I can't get my ahead around it, they seem identical to me.

Is there really any difference between using 'total' and 'd * d'???

Thank you

1 Answer 1

1

Both appear to work. I ran the following test program and it works fine, printing out for both when d=4. Is it possible that you have some other difference in code somewhere?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>


int main(int argc, char* argv[])
{
    int d = atoi(argv[1]);
    printf("d = %i\n",d);

    int total = d * d; 

     if (((d*d)-1) % 2 != 0) printf("ping d\n");

     if ((total-1) % 2 != 0) printf("ping total \n");

}

[EDIT: updated answer.]

This is what happens when I look in the wrong place. Sure, my test program works fine, but I completely overlooked something. While total is initially calculated to be d*d, the code changes the content of total, decrementing it to 0 in the nested for loops that follow. Bottom line, total = 0 when you're trying to use it to check whether to swap.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

3
  • I really don't think so. If I cut and paste in both lines of code, I get two completely different results. Literally the only thing that changes is total vs d * d
    – gloopit
    Jul 8, 2016 at 17:58
  • See my edited answer.
    – Cliff B
    Jul 8, 2016 at 18:43
  • What a fool I am, thank you!
    – gloopit
    Jul 8, 2016 at 18:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .