My Boggle Solver: I welcome any tips and tricks!

S

Stedwick

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 }
 
W

William James

$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
}
}
 
W

William James

$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
}}

Shorter:

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

ThoML

$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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top