Reputation: 9
I've built a 15 puzzle in JS but my random puzzle generation is creating instances of an unsolvable puzzle. This could be because I'm not a Computer Science head, but I'm not sure how to work out things like calculate the number of inversions in a permutation in code. I'm wondering how to write my code so that I can test that any given start state of my puzzle is solvable. I've seen other 15 puzzles in published apps out there that are unsolvable, so it seems I'm not the only one out there with my problem.
I've seen this post, but it stops at the CS level and I'm looking for a code implementation that would help me understand this a little better: 15 Puzzle Heuristic
I'm using JS, but any help and explanation from whichever language would be a great help.
Upvotes: 0
Views: 5172
Reputation: 49331
The algorithm for solvability is based on the parity of inversion and explained in 15 Puzzle - Wolfram Math World It should not be too difficult to convert into code. IIRC swapping two adjacent squares on a non-solvable starting point makes it solvable, but you will need to confirm that.
Note that this is an exact algorithm determining whether or not a puzzle can be solved, not a heuristic for guiding the sequence of steps in the solution.
Upvotes: 3
Reputation: 101614
What I was eluding to in a comment, but wasn't sure if it the right approach:
Since you're starting with a valid board, then applying a set of forced mis-directions, you'll always end up a completely legitimate start game.
Upvotes: 2