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 }