Save the indexs of a multi-dimensional arrays ...

Hello, I am working on the game of fifteen.Yes this is home work. I was wondering if it is possible to save the indexes of an element in a two dim array. I need to find the position of the space in the two dim array save it, find the position of the tile which is passed in as an int and swap the two if they are adjacent. Here is my code i hope the helps explain what I am trying to do better.I am very sorry I just don't know how to explain this.

Edit: I can do this by saving i and j in separate int variables but is there a more elegant way of doing this thanks alot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
int board[MAX][MAX];

void init();

void swap(int* lhs, int* rhs);

void draw();

bool move(int tile);

bool islegal( );

int main (int argc, char** argv)
{
    init();
    draw();
    printf("%d\n",move(77)); //just checking if it found the space
}

/**
  * populate board
  */
void init(void)
{
    int tile_numbers = (MAX * MAX) - 1;

    for (int i = 0; i < SIZE; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            board[i][j] = tile_numbers;
            tile_numbers--;
        }
    }
    
    // if number of tiles is odd swap 1 && 2
    if (((MAX * MAX) -1) % 2 != 0)
        swap(&board[SIZE][SIZE - 2], &board[SIZE][SIZE -1 ]);
}

/**
 * Swap helper function 
 */
void swap(int* lhs, int* rhs)
{
   int temp =  *rhs;
   *rhs = *lhs;
   *lhs = temp;
}

/**
 * draw board to screen
 */
void draw()
{
    for (int i = 0; i < SIZE; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            if(board[i][j] == 0)
                printf("%3c", ' ');

            else
                printf("%3i", board[i][j]);
        }
       printf("\n");
    }
   // printf("%i\n", board[SIZE-1][SIZE-1]);
}

/**
 *Move tile number 'tile'
 */
bool move(int tile)
{   
    // starting position of space
    int space = board[SIZE-1][SIZE-1]; 
    space++; //remove this just moving space temp to see if it finds it

    // Find tile position in array
    for (int i = 0; i < SIZE; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            if (board[i][j] == tile)
            {

                return true;
            }
        }
    }
    return false;

}

/**
 * verify move is legal
 */
bool islegal(int tile, int space)
{
  // not adjacent 
   return false;
}
Last edited on
http://www.cplusplus.com/forum/articles/17108/
Look at the Killing MD: 1D Mimics
Of course you can have additional integral variables to store interesting indices.

Your line 38, however, has two out-of-range errors.
Thanks guys
Topic archived. No new replies allowed.