Random

Created May 26, 2025 (Today)Updated May 26, 2025 (Today)

Random Walks

In Code:

class Walker {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    step() {
        let choice = Math.floor(Math.random() * 4)
        // 0, 1, 2, or 3. The random choice determines the step.
        // TODO: define 8 possible directions (include diagonals)

        if (choice === 0) {
            this.x++
        } else if (choice === 1) {
            this.x--
        } else if (choice === 2) {
            this.y++
        } else {
            this.y--
        }
    }

    draw(ctx, size = 10) {
        ctx.beginPath()
        ctx.arc(this.x, this.y, size, 0, Math.PI * 2)
        ctx.fill()
    }
}

Further Exploration

  • Biased random walks
  • Random walks in higher dimensions
  • Random walks with missing directions
  • Create a random walker that has a greater tendency to move down and to the right. (A partial solution follows in the next section.)

Resources