Xankar Xankar - 4 years ago 70
C++ Question

Swapping two values within a 2D array

I am currently working on a 15 puzzle programming assignment. My question here is about how I would go about swapping the empty tile with an adjacent tile.

So, for example, let's go with the initial setup board.
I have:

int originalBoard[4][4] = {
{1 , 2, 3, 4},
{5 , 6, 7, 8},
{9 ,10,11,12},
{13,14,15, 0}};

So here, the locations of 12, 15, and 0 (the empty tile) in the array are [3][4], [4][3], and [4][4] respectively. What would be a method of swapping 0 out with either 12 or 15?

What I had in mind for this was creating a loop that would keep track of the empty tile every time I made a move.

I believe an optimal method would be to have two functions. 1 that would update the location of the empty tile, and 1 to make the move.

So, right off the top of my head I would have:

void locateEmptyTile(int& blankRow, int& blankColumn, int originalBoard[4][4])
for (int row = 0; row < 4; row++)
for (int col = 0; col < 4; col++)
if (originalBoard[row][col] == 0)
blankRow = row;
blankColumn = col;

void move(int& blankRow, int& blankColumn, int originalBoard[4][4])


And in my
function I would have the variables:
int blankRow
int blankColumn

Now, how would I take that data from
and apply it into the
function in the relevant practical manner? The process does not currently connect within my head.

I appreciate any little bits of help.

Answer Source

A basic swap concept (pre-C++11) is hold a temporary variable. Simply...

template<typename T, typename U>
void swap(T& lhs, U& rhs) {
    T t = lhs;
    lhs = rhs;
    rhs = t;

So, you don't need to reference blankRow and blankCol, you just need to reference the values on the grid. Lets say that you want to swap what you know is blank positioned at (2, 1) with (2, 2)...

swap(originalBoard[2][1], originalBoard[2][2]);

... will swap the values within originalBoard.

If you are using C++11 or later, just use std::swap() to swap positions. That's exactly what it does.

If you would like originalBoard to be immutable an result in a totally different board, just copy it first before applying the switch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download