Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created June 18, 2012 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/2947179 to your computer and use it in GitHub Desktop.
Save rklemme/2947179 to your computer and use it in GitHub Desktop.
Grid example
class Grid
def initialize(dim_x, dim_y)
@x = dim_x
@y = dim_y
@store = {}
end
def [](coord)
@store[validate_coord coord]
end
def []=(coord, dat)
raise sprintf("invalid data: %p", dat) unless nd_valid(dat)
c = validate_coord coord
if dat
@store[c] = dat
else
@store.delete c
end
end
def replace(dat)
# first check to make change atomic
dat.all? {|c, d| coord_valid(c) && nd_valid(d)} or raise sprintf("invalid data: %p", dat)
dat.each do |c, d|
self[c] = d
end
end
private
def validate_coord(c)
raise sprintf("invalid coord: %p", c) unless coord_valid(c)
c
end
def coord_valid(c)
Coord === c && c.x >= 0 && c.x < @x && c.y >= 0 && c.y < @y
end
def nd_valid(nd)
nd.nil? || NodeData === nd
end
end
class Coord
attr_reader :x, :y
def initialize(x, y)
raise sprintf("invalid coords: x=%p y=%p", x, y) if x < 0 || y < 0
@x = x.to_int
@y = y.to_int
freeze
end
def eql?(c)
c.x == @x && c.y == @y
end
alias == eql?
def hash
((@x << 3) ^ @y) & 0xFFFF
end
end
def Coord(x, y) Coord.new(x, y) end
NodeData = Struct.new :name, :info, :more_info
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment