My Boggle Solver: I welcome any tips and tricks!

So, I wrote a Boggle solver so that I could win at Scramble and
Griddle on Facebook, and it works great! However, I’m pretty new at
Ruby, so if you know any “rubyisms” or “ruby ways” that would help
clean up my program, feel free to give some pointers =) Code below:

$words = {}
$stems = {}
File.open(“enable.txt”,“r”).each do |line|
word = line.chomp
$words[word] = true

0.upto(word.size-2) do |i|
$stems[word[0…i]] = true
end
end

puts “Enter Boggle board as a string of letters:”
letters = gets.chomp

$H = 4
$W = 4
if letters.size != $H*$W
puts “Wrong board size.”
exit
end

i=0
$board = Array.new($H) { Array.new($W) }
0.upto($H-1) do |h|
0.upto($W-1) do |w|
$board[h][w] = letters[i…i]
i+=1
end
end

$used = Array.new($H) { Array.new($W) { false } }

$found = {}
def solve(h, w, word = ‘’)
$used[h][w] = true
word += $board[h][w]
$found[word] = true if word.size > 2 and $words[word]

if $stems[word]
-1.upto(1) do |r|
-1.upto(1) do |c|
y = h+r
x = w+c
next unless (0…$H-1) === y
next unless (0…$W-1) === x
next if $used[y][x]
solve(y, x, word)
end
end
end

$used[h][w] = false
end

0.upto($H-1) do |h|
0.upto($W-1) do |w|
solve(h,w)
end
end

found_words = $found.keys.sort_by { |x| x.size }
found_words.each { |x| puts x }
puts
$board.each { |x| puts x.to_s }

On Feb 15, 11:34 pm, Stedwick [email protected] wrote:

$words = {}
$stems = {}
File.open(“enable.txt”,“r”).each do |line|
word = line.chomp
$words[word] = true

0.upto(word.size-2) do |i|
$stems[word[0…i]] = true
end
end

IO.foreach(“enable.txt”){|word|
word.strip!
$words[word] = true
(0…word.size).each{|i|
$stems[ word[0,i] ] = true
}
}

On Feb 16, 12:17 am, William J. [email protected] wrote:

end
end

IO.foreach(“enable.txt”){|word|
word.strip!
$words[word] = true
(0…word.size).each{|i|
$stems[ word[0,i] ] = true
}}

Shorter:

IO.foreach(“data”){|word|
$words[ word.strip! ] = true
(0…word.size).each{|i|
$stems[ word[0,i] ] = true
}
}

$words = {}

IMHO you might also want to try to avoid using global variables. A
better solution usually is to use “normal” variables or to wrap it up
in a class/module and use class/instance variables. Or collect the
parameters in a hash and pass that around.