Workshop › 15 Puzzle › Step 18 of 27

Which boards can be solved?

What we are doing

Half of all arrangements of this puzzle can never be solved. A rule tells them apart: count the pairs of tiles in the wrong order, add the gap's row counted from the bottom; the board can be solved exactly when the sum is odd. solvable(list) checks it, so we can prove our shuffle keeps its promise.

```js
// A position can be solved when the number of pairs out of order, plus the gap's row counted from the bottom, is odd.
function solvable(list) {
  const numbers = list.filter((t) => t !== 0)
  let inversions = 0
  for (let a = 0; a < numbers.length; a++) {
    for (let b = a + 1; b < numbers.length; b++) if (numbers[a] > numbers[b]) inversions++
  }
  const gapRowFromBottom = N - rowOf(list.indexOf(0))
  return (inversions + gapRowFromBottom) % 2 === 1
}
```

What it means

Your turn

Above function reset(), write the comment and solvable, and leave an empty line. Press Run.

Skills: Loops

All steps

  1. A board in one list
  2. The canvas and the pen
  3. Paint the table
  4. A function that draws
  5. Row and column
  6. Where each square is
  7. Draw one tile
  8. The number on the tile
  9. All the tiles
  10. Draw again and again
  11. The solved board from N
  12. Neighbours
  13. Slide a tile
  14. Click a tile
  15. Arrow keys
  16. Count the moves
  17. Shuffle with real slides
  18. Which boards can be solved?
  19. Is it solved?
  20. Remember the slide
  21. Count the frames
  22. Smooth sliding
  23. Solved!
  24. Show the win
  25. Play again
  26. A record to beat
  27. Build it yourself: a timer