Created
December 5, 2014 08:44
-
-
Save EmmanuelOga/0011abb7b76da1291f16 to your computer and use it in GitHub Desktop.
Quick and Dirty Boggle-Like game algo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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