Slider puzzle

The first time I created a slider puzzle, I simply shuffled the pieces, not realizing that only half the permutations are solvable. People who visited my website must have scratched their head.

There are two ways to address this:

1) You can shuffle the grid by making a certain number of random legal moves, this way you can never put the grid in an unsolvable state, and it has the added benefit that you can nicely animate the shuffle.

2) Or you can shuffle the grid, and check if it is solvable, otherwise you shuffle again until it is. But how do you know that you have a solvable permutation? Well, it depends on the evenness of the rows and columns, the position of the blank space, and the number of inversions.

Whenever a tile is preceded by a tile with a higher index value it counts as an inversion. In our case, with the blank space in the home position, the number of inversions must be even for the puzzle to be solvable.

Go ahead and try it, scramble the delicious burger and make it whole again. If you've solved the puzzle, and you have the JavaScript2RealBurger™ plugin installed, you will be able to actually eat it.

View code on Github