问题是这样的:给定一个单词,计算该单词的拼字游戏分数。
我创建了一个字典来跟踪字符及其相关的拼字游戏点。我创建了一个函数来迭代字典数组中的每个字符,如果它包含迭代的字符,则会添加一个点。不幸的是,该函数无法统计重复的字符,我似乎无法理解为什么......
// struct contains the Scrabble Points dictionary
struct Scrabble {
static let scrabblePoints = [1 : ["AEIOULNRST"],
2 : ["DG"],
3 : ["BCMP"],
4 : ["FHVWY"],
5 : ["K"],
8 : ["JX"],
10 : ["QZ"]]
}
var points = 0
// I can't figure out why my function doesn't iterate over repeated characters...
func pointGenerator(word:String) -> Int {
for (key, letters) in Scrabble.scrabblePoints {
for i in letters {
for j in i {
if word.contains(j) {
points += key
}
}
}
}
return points
}
//score is inaccurate.
最佳答案
您正在测试什么词?问题似乎在于您可能将小写字符与大写拼字游戏字符进行比较。
话虽如此,我认为您的解决方案有点过于复杂。例如,为什么 ScrabblePoints 中的值是一个数组?如果值只是字符串,您可以消除 generatePoints
中的 for
循环之一。
更重要的是,让我们重新考虑设置 scrabblePoints
的方式。字典的目的是为您提供直接查找。通过迭代字符,您将消除字典的好处。相反,如果您像这样构建字典会怎样:
static let scrabblePoints = ['A' : 1,
'B' : 3,
'C' : 3,
// and so on for all 26 letters
]
这样,您就可以直接查找任何给定角色的分值。所以你的generatePoints
变成:
func pointGenerator(word: String) -> Int {
for char in word {
points += Scrabble.scrabblePoints[char.uppercased()]
}
return points
}
关于arrays - 如何创建一个函数来将字符串与字典中的字符串数组进行比较并根据键分配点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67906170/