Skip to content

Commit 3924261

Browse files
committed
Section 22: Shuffling Neighbor Pairs
1 parent ba37ce7 commit 3924261

2 files changed

Lines changed: 28 additions & 8 deletions

File tree

22-Javascript-with-the-Canvas-API/02-Maze copy/index.js

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,22 @@ World.add(world, walls)
3232

3333
// Maze generation
3434

35+
const shuffle = (arr) => {
36+
let counter = arr.length
37+
38+
while(counter > 0 ) {
39+
const index = Math.floor(Math.random() * counter)
40+
41+
counter--
42+
43+
const temp = arr[counter]
44+
arr[counter] = arr[index]
45+
arr[index] = temp
46+
}
47+
48+
return arr
49+
}
50+
3551
const grid = Array(cells)
3652
.fill(null)
3753
.map(() => Array(cells).fill(false))
@@ -60,12 +76,13 @@ const stepThroughCell = (row, column) => {
6076
grid[row][column] = true
6177

6278
// Assemble randomly-ordered list of neighbors
63-
const neighbors = [
79+
const neighbors = shuffle([
6480
[row - 1, column],
6581
[row, column + 1],
6682
[row + 1, column],
6783
[row, column - 1],
68-
]
84+
])
85+
console.log(neighbors);
6986

7087
// For each neighbor....
7188

@@ -78,5 +95,6 @@ const stepThroughCell = (row, column) => {
7895
// Visit that next cell
7996
}
8097

81-
stepThroughCell(startRow, startColumn)
82-
console.log(grid)
98+
// stepThroughCell(startRow, startColumn)
99+
stepThroughCell(1, 1)
100+
// console.log(grid)

22-Javascript-with-the-Canvas-API/README.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,13 @@ World.add(world, shape)
4040
// Maze generation
4141
const grid = []
4242

43-
for(let i = 0; i < 3; i++) {
43+
for (let i = 0; i < 3; i++) {
4444
grid.push([])
45-
for(let j = 0; j < 3; j++) {
45+
for (let j = 0; j < 3; j++) {
4646
grid[i].push(false)
4747
}
4848
}
49-
console.log(grid);
49+
console.log(grid)
5050
```
5151

5252
```javascript
@@ -61,4 +61,6 @@ console.log(grid)
6161

6262
## 11. 15 Guiding Comments
6363

64-
## 12. 16 Neighbor Coordinates
64+
## 12. 16 Neighbor Coordinates
65+
66+
## 13. 17 Shuffling Neighbor Pairs

0 commit comments

Comments
 (0)