【发布时间】:2021-08-26 13:51:15
【问题描述】:
问题是:给定一个单词,计算该单词的拼字游戏分数。
我创建了一个字典来跟踪字符及其相关的拼字游戏点。我创建了一个函数来迭代字典数组中的每个字符,如果它包含迭代的字符,它会添加一个点。不幸的是,该函数无法统计重复的字符,我似乎无法理解为什么......
// 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.
【问题讨论】:
-
检查大小写?
-
您应该用单词迭代每个
character。但是,如果您想在伪代码中保留当前循环,而不是word.contains(j),但您可能会看到它为什么不起作用,请使用word.count(for: j)(您需要编写count(for:)? -
@Sh_Khan 很好——我需要应用一种方法来做到这一点
-
@Larme 感谢您的回复!我不确定我是否理解如何应用您的建议?
-
意思是pastebin.com/W4222eNw 但仍然如此。您的方法将分数添加到单词的总分中,而它应该获得该单词的分数,然后将其添加到满分中。
标签: arrays swift function dictionary