Loading

C++: Fifteen Puzzle

Fifteen Puzzle

In this C++ tutorial, we program the Fifteen Puzzle using material from previous lessons. The Fifteen Puzzle consists of a set of 15 numbered squares set into a 4x4 array with one square empty. Squares adjacent to the empty square can slide into it. For our purposes, we simply swap the two values in our array.

The squares are numbered 1 through 15, and we use hexadecimal for our numbering in order to make the printing in the console window look nicer. With hexadecimal, each square is one character so that the printed board is just a 4x4 set of characters with one left blank:

The objective of the puzzle is to get the squares ordered from 1 through 15 or F from right to left and top to bottom, like this:

To keep the code simple, we have eliminated checks to see whether the puzzle is solved and corresponding messages. Instead, we have left that for you to add, if you like. There are probably other features you could add as well.

For anyone who is not familiar with hexadecimal, it is a base 16 number system where each digit can represent sixteen different values. If you have not worked with different number bases before, that might be confusing. We will cover number bases later, since they are extremely important in computer programming. For this puzzle, it suffices to understand that A through F equal 10 through 15, respectively.