Assign Integers From Dictionary Values To Characters Of A String
Solution 1:
n[i]
is of type Character
, so that should be the key type
of the dictionary instead of String
. The value type should be Int
:
let dict: [Character: Int] = ["a": 1, "j": 1, "s": 1, "b": 2, "k": 2, "r": 9 /* ... */]
You also have to define a "default value" which is used as score
for characters not found in the dictionary, this can be done
with the nil-coalescing operator ??
:
let n = "lighthouse"
var nScore = 0
for i in n.indices[n.startIndex..<n.endIndex] {
let curChar = n[i]
let curVal = dict[curChar] ?? 0
nScore = nScore + curVal
}
Or simpler, by enumerating the characters of the string directly:
for c in n {
let curVal = dict[c] ?? 0
nScore = nScore + curVal
}
Even shorter with reduce()
:
let n = "lighthouse"
let nScore = n.reduce(0) { (score, c) in
score + (dict[c] ?? 0)
}
which can be written more compactly using "shorthand parameters":
let n = "lighthouse"
let nScore = n.reduce(0) { $0 + (dict[$1] ?? 0) }
If it you have full control over the possible characters which can occur in the input string, and it is guaranteed(!) the dictionary defines values for all of them then you can force-unwrap the dictionary lookup, for example
let n = "lighthouse"
let nScore = n.reduce(0) { $0 + dict[$1]! }
But this will crash at runtime if a character is not found.
If you define a function
func numericScore(_ str: String) -> Int {
return str.reduce(0) { $0 + (dict[$1] ?? 0) }
}
then you can easily apply it to a single string
let nScore = numericScore("lighthouse")
or map it over an array of strings
let words = ["lighthouse", "motorcycle"]
let scores = words.map(numericScore)
or compute the total score for an array of strings (using reduce
again):
let words = ["lighthouse", "motorcycle"]
let totalScore = words.reduce(0) { $0 + numericScore($1) }
// Alternatively in two steps:
let scores = words.map(numericScore)
let totalScores = scores.reduce(0, +)
Post a Comment for "Assign Integers From Dictionary Values To Characters Of A String"