(c) Exercism
Given a word, compute the scrabble score for that word.
Letter Values You'll need these:
Letter Value
A, E, I, O, U, L, N, R, S, T 1
D, G 2
B, C, M, P 3
F, H, V, W, Y 4
K 5
J, X 8
Q, Z 10
Examples
"cabbage" should be scored as worth 14 points:
3 points for C
1 point for A, twice
3 points for B, twice
2 points for G
1 point for E
And to total:
3 + 2*1 + 2*3 + 2 + 1
= 3 + 2 + 6 + 3
= 5 + 9
= 14
import Foundation
class Scrabble {
class func score(_ word: String) -> UInt {
var score: UInt = 0
let lowercasedWord = word.lowercased()
let points: [String.Element: UInt] = [
"a" : 1, "e" : 1, "i" : 1, "o" : 1, "u" : 1,
"l" : 1, "n" : 1, "r" : 1, "s" : 1, "t" : 1,
"d" : 2, "g" : 2,
"b" : 3, "c" : 3, "m" : 3, "p" : 3,
"f" : 4, "h" : 4, "v" : 4, "w" : 4, "y" : 4,
"k" : 5,
"j" : 8, "x" : 8,
"q" : 10, "z" : 10,
"ñ" : 15
]
for char in lowercasedWord {
let point = points[char] ?? 0
score += UInt(point)
}
return score
}
}
import XCTest
@testable import Scrabble
/*
Letter Value
A, E, I, O, U, L, N, R, S, T 1
D, G 2
B, C, M, P 3
F, H, V, W, Y 4
K 5
J, X 8
Q, Z 10
Ñ 15
*/
class ScrabbleTest: XCTestCase {
struct Test {
let input: String
let output: UInt
}
func testCases() {
let cases = [
Test(input: "", output: 0),
Test(input: "AaaAAA", output: 6),
Test(input: "eeEE", output: 4),
Test(input: "iIIi", output: 4),
Test(input: "oOOOO", output: 5),
Test(input: "uUuu", output: 4),
Test(input: "LLl", output: 3),
Test(input: "NnNNN", output: 5),
Test(input: "RRRr", output: 4),
Test(input: "sSS", output: 3),
Test(input: "TtTTTT", output: 6),
Test(input: "DdDDDDD", output: 14),
Test(input: "gGG", output: 6),
Test(input: "Bb", output: 6),
Test(input: "ccC", output: 9),
Test(input: "MmMM", output: 12),
Test(input: "pPPPP", output: 15),
Test(input: "FfFFf", output: 20),
Test(input: "HhHH", output: 16),
Test(input: "VvV", output: 12),
Test(input: "Ww", output: 8),
Test(input: "Yy", output: 8),
Test(input: "kK", output: 10),
Test(input: "Jj", output: 16),
Test(input: "Xx", output: 16),
Test(input: "Qq", output: 20),
Test(input: "Zz", output: 20),
Test(input: "Ññ", output: 30),
Test(input: "C h i C h i", output: 16),
]
for c in cases {
let word = c.input
let expected = c.output
let actual = Scrabble.score(word)
XCTAssertEqual(actual, expected, "Input: " + c.input)
}
}
}