Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created December 5, 2014 08:44
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 EmmanuelOga/0011abb7b76da1291f16 to your computer and use it in GitHub Desktop.
Save EmmanuelOga/0011abb7b76da1291f16 to your computer and use it in GitHub Desktop.
Quick and Dirty Boggle-Like game algo
def initialize(words)
@words = words
end
def isWord?(word)
@words.include?(word)
end
# TODO: implement trie :)
def isPrefix?(word)
@words.any? { |w| w.start_with?(word) }
end
end
class Coord
attr_reader :x, :y
def initialize(x, y, max)
@x, @y, @max = x, y, max
end
def surrounding
(-1..1).map do |i|
(-1..1).map do |j|
c = Coord.new(@x + i, @y + j, @max)
c if c.inBound? && !c.eql?(self)
end
end.flatten.compact
end
def eql?(other)
@x == other.x && @y == other.y
end
def inBound?
@x < @max && @x >= 0 && @y < @max && @y >= 0
end
def offset
@x * @max + @y
end
def to_s
"#{@x},#{@y}."
end
alias inspect to_s
end
class Boggle
def initialize(dict, grid)
@dict = dict
@grid = grid
@size = Math.sqrt(grid.length).to_i
end
def get(coord)
@grid[coord.offset]
end
def walkPath(coord, memory = [], &block)
memory = memory + [coord]
word = memory.map { |c| get(c) }.join
block.call word if @dict.isWord?(word)
if @dict.isPrefix?(word)
pending = coord.surrounding.reject { |c| memory.any? { |m| m.eql?(c) } }
pending.each { |c| walkPath(c, memory, &block) }
end
end
def eachWord(&block)
(0...@size).each do |x|
(0...@size).each do |y|
walkPath Coord.new(x, y, @size), [], &block
end
end
end
def to_s
@grid.inspect
end
end
d = Dict.new %w{cat dog dodgy serpent snake}
g = Boggle.new d, %w{
d b c o d
o a g b i
d j t c t
g y z y n
s e r p e
}
g.eachWord do |word|
puts "Found: #{word}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment