July 2015
Intermediate to advanced
286 pages
6h 31m
English
The following uses an array to keep track of all unvisited cells in the grid. Besides letting us query whether a cell has been visited or not, this also lets us quickly choose an unvisited cell from which to start our loop-erased random walk.
Put the following code in a file named wilsons.rb.
| wilsons.rb | |
| Line 1 | class Wilsons |
| - | |
| - | def self.on(grid) |
| - | unvisited = [] |
| 5 | grid.each_cell { |cell| unvisited << cell } |
| - | |
| - | first = unvisited.sample |
| - | unvisited.delete(first) |
| - | |
| 10 | while unvisited.any? |
| - | cell = unvisited.sample |
| - | path = [cell] |
| - | |
| - | while unvisited.include?(cell) |
| 15 | cell = cell.neighbors.sample |
| - | position = path.index(cell) |
| - | if position |
| - | path = path[0..position] |
| - | else |
Read now
Unlock full access