DEV Community

Discussion on: What are your favorite books?

Collapse
 
chenge profile image
chenge

Could you share some example code of mazes book so let us know if we can understand it?

Thread Thread
 
deciduously profile image
Ben Lovy • Edited

Sure, here's a partial (but functional) implementation of the Cell class used in the book. It is not advanced Ruby, but the author does not spend any time teaching Ruby concepts - this code snippet appears early on in the first chapter and the assumption is the reader can understand it:

class Cell
  attr_reader :row, :column
  attr_accessor :north, :south, :east, :west

  def initialize(row, column)
    @row, @column = row, column
    @links = {}
  end

  def link(cell, bidi=true)
    @links[cell] = true
    cell.link(self, false) if bidi
    self
  end

  def unlink(cell, bidi=true)
    @links.delete(cell)
    cell.unlink(self, false) if bidi
    self
  end

  def links
    @links.keys
  end

  def linked?(cell)
    @links.key?(cell)
  end

  def neighbors
    list = []
    list << north if north
    list << south if south
    list << east if east
    list << west if west
    list
  end
end

And the simplest algorithm:


class BinaryTree
  def self.on(grid)
    grid.each_cell do |cell|
      neighbors = []
      neighbors << cell.north if cell.north
      neighbors << cell.east if cell.east

      index = rand(neighbors.length)
      neighbor = neighbors[index]

      cell.link(neighbor) if neighbor
    end

    grid
  end
end

Basic building blocks, but you do need to know what, for example, attr_accessor means

I'm following along in TypeScript and finding the translation straightforward.

Thread Thread
 
chenge profile image
chenge

Thanks, I almost understand it.