【发布时间】:2012-09-02 15:57:01
【问题描述】:
我正在尝试创建一个基于 4x4 字母网格的单词生成器(如下)。
规则如下:
- 字母不能重复
- 单词必须由相邻的字母组成
- 单词可以水平、垂直或对角向左、向右或向上和向下构成
目前,我输入 16 个字符并循环遍历字典中的每个单词,确定该单词是否可以用网格上的字母拼写。
#!/usr/bin/ruby
require './scores' # alphabet and associated Scrabble scoring value (ie the wordValue() method)
require './words.rb' # dictionary of English words (ie the WORDS array)
# grab users letters
puts "Provide us the 16 letters of your grid (no spaces please)"
word = gets.chomp.downcase
arr = word.split('')
# store words that can be spelled with user's letters
success = []
# iterate through dictionary of words
WORDS.each do |w|
# create temp arrays
dict_arr = w.split('')
user_arr = arr.dup
test = true
# test whether users letters spell current word in dict
while test
dict_arr.each do |letter|
if (user_arr.include?(letter))
i = user_arr.index(letter)
user_arr.delete_at(i)
else
test = false
break
end
end
# store word in array
if test
success << w
test = false
end
end
end
# create hash for successful words and their corresponding values
SUCCESS = {}
success.each do |w|
score = wordValue(w)
SUCCESS[w] = score
end
# sort hash from lowest to smallest value
SUCCESS = SUCCESS.sort_by {|word, value| value}
# print results to screen
SUCCESS.each {|k,v| puts "#{k}: #{v}"}
但是,这种方法没有考虑棋盘上棋子的位置。 您建议我如何根据 4x4 网格中的位置来查找可以创建的单词?
对于上图中的棋盘游戏,我运行 Ubuntu 的 VM 需要大约 1.21 秒来计算 1185 个可能的单词。我在 /usr/share/dict/words 中使用 Ubunut 提供的单词词典
【问题讨论】:
标签: ruby string algorithm grid permutation