Workshop › 15 Puzzle › Step 17 of 27
A puzzle must start mixed. We start from the solved board and make 200 random slides, never undoing the one just made. Every board reached like this can be solved by playing the slides backwards.
```js
// Mix the tiles by making random slides, so the puzzle can always be solved.
function shuffle(count) {
let gap = tiles.indexOf(0)
let previous = -1
for (let n = 0; n < count; n++) {
const options = neighbors(gap).filter((i) => i !== previous) // do not undo the last slide
const i = options[Math.floor(Math.random() * options.length)]
tiles[gap] = tiles[i]
tiles[i] = 0
previous = gap
gap = i
}
}
tiles = solvedTiles()
shuffle(200)
```for loop repeats count times.options are the gap's neighbours, except the square the gap just came from (previous), so no slide is undone.Math.random() gives a number from 0 up to 1; times the length, rounded down, it picks a random option.function reset(), write the comment and shuffle, and leave an empty line.reset, under tiles = solvedTiles(), write shuffle(200). Press Run a few times.Skills: Loops, Arrays and objects
← Count the moves Which boards can be solved? →