1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<html>
<body>
<table id='grid'></table>
<script>
const SIZE = 30 // width and height of the grid
const DELAY = 500 // delay in ms between steps of the walk
// Build the SIZE x SIZE grid
const table = document.getElementById('grid')
// `grid[i][j]` stores the table cell in row `i` and column `j`,
// as well as the number of times it has been visited during the walk
const grid = []
for (let i = 0; i < SIZE; i++) {
// `tr` is a "table row" element
const rowElement = document.createElement('tr')
const row = []
for (let j = 0; j < SIZE; j++) {
// `td` is a "table cell" element
const element = document.createElement('td')
rowElement.appendChild(element)
row.push({element, count: 0})
}
table.appendChild(rowElement)
grid.push(row)
}
// Visit a given grid position and
// display the number of times it has been visited
function visit(position) {
// Don't do anything if we're off the grid
const row = grid[position.row]
if (row === undefined) return
const cell = row[position.col]
if (cell === undefined) return
cell.count++
cell.element.innerText = String(cell.count)
}
// Compute the next position by randomly going left, right, up, or down
function nextPosition(position) {
const {row, col} = position
const random = Math.random()
if (random < 0.25) return {row: row + 1, col}
else if (random < 0.5) return {row: row - 1, col}
else if (random < 0.75) return {row, col: col + 1}
else return {row, col: col - 1}
}
// Start in the middle of the grid and jump every DELAY ms
let position = {row: Math.floor(SIZE / 2), col: Math.floor(SIZE / 2)}
visit(position)
setTimeout(() => {
// First movement
position = nextPosition(position)
visit(position)
setTimeout(() => {
// Second movement
position = nextPosition(position)
visit(position)
setTimeout(() => {
// Third movement
position = nextPosition(position)
visit(position)
}, DELAY)
}, DELAY)
}, DELAY)
</script>
<style>
#grid {
border-collapse: collapse;
}
#grid td {
border: 1px solid black;
width: 20px;
height: 20px;
font-size: 15px;
font-family: sans-serif;
text-align: center;
}
</style>
</body>
</html>