ferencd@0: #--- ferencd@0: # Excerpted from "Mazes for Programmers", ferencd@0: # published by The Pragmatic Bookshelf. ferencd@0: # Copyrights apply to this code. It may not be used to create training material, ferencd@0: # courses, books, articles, and the like. Contact us if you are in doubt. ferencd@0: # We make no guarantees that this code is fit for any purpose. ferencd@0: # Visit http://www.pragmaticprogrammer.com/titles/jbmaze for more book information. ferencd@0: #--- ferencd@0: class Wilsons ferencd@0: ferencd@0: def on(grid) ferencd@0: unvisited = [] ferencd@0: grid.each_cell { |cell| unvisited << cell } ferencd@0: ferencd@0: first = unvisited.sample ferencd@0: unvisited.delete(first) ferencd@0: ferencd@0: while unvisited.any? ferencd@0: cell = unvisited.sample ferencd@0: path = [cell] ferencd@0: ferencd@0: while unvisited.include?(cell) ferencd@0: cell = cell.neighbors.sample ferencd@0: position = path.index(cell) ferencd@0: if position ferencd@0: path = path[0..position] ferencd@0: else ferencd@0: path << cell ferencd@0: end ferencd@0: end ferencd@0: ferencd@0: 0.upto(path.length-2) do |index| ferencd@0: path[index].link(path[index + 1]) ferencd@0: unvisited.delete(path[index]) ferencd@0: end ferencd@0: end ferencd@0: ferencd@0: grid ferencd@0: end ferencd@0: ferencd@0: end