Scrabble单词分数计算函数开发及重复字符统计异常排查求助
Let's break down why your pointGenerator isn't counting repeated characters correctly, then fix it step by step!
What's Going Wrong in Your Code?
There are two critical issues causing the inaccurate scores:
Global
pointsvariable: You're using a global variable to track scores, which means every time you callpointGenerator, it adds to the existing total instead of starting fresh. Even if you fixed the character counting logic, this would still break multiple function calls.Backwards traversal logic: Right now, your code loops through each point value and its associated letters, then checks if the word contains that letter. If it does, you add the point value once—regardless of how many times the letter appears in the word. For example, "AA" would only add 1 point instead of 2, because you're just verifying "A" exists, not counting its occurrences.
The Fixed Solution
Here's a revised version of your code that addresses both issues, plus some extra improvements for robustness:
struct Scrabble { // Simplified the points dictionary (no need for arrays of single strings) static let scrabblePoints: [Int: String] = [ 1: "AEIOULNRST", 2: "DG", 3: "BCMP", 4: "FHVWY", 5: "K", 8: "JX", 10: "QZ" ] // Helper method to get the score for a single character static func score(for character: Character) -> Int { let upperChar = character.uppercased() for (pointValue, letters) in scrabblePoints { if letters.contains(upperChar) { return pointValue } } return 0 // Return 0 for non-scoring characters } } func pointGenerator(word: String) -> Int { var totalPoints = 0 // Local variable resets every function call for character in word { totalPoints += Scrabble.score(for: character) } return totalPoints }
Key Changes Explained
- Local score tracking: Replaced the global
pointswith a localtotalPointsvariable inside the function. This ensures each call topointGeneratorstarts calculating from 0. - Character-first traversal: Instead of looping through the points dictionary first, we iterate over each character in the input word. This way, every occurrence of a character (even repeats) gets its score added individually.
- Case insensitivity: The helper method converts characters to uppercase, so inputs like "aa" or "Aa" will score the same as "AA".
- Cleaner dictionary structure: Removed unnecessary arrays from the
scrabblePointsdictionary—since each point value maps to a single string of letters, we can use[Int: String]directly for simplicity.
Testing It Out
Try these examples to verify it works:
pointGenerator(word: "AA")returns2(correct, since each A is worth 1 point)pointGenerator(word: "QUIZ")returns22(10 for Q, 1 for U, 10 for Z, 1 for I)pointGenerator(word: "HELLO")returns8(4 for H, 1 for E, 1 for L, 1 for L, 1 for O)
内容的提问来源于stack exchange,提问作者Zachary Schiller

