= Solution
Reject the empty <string>, because the given formula would divide by zero and no normalized <probability distribution> exists on its empty observed support. Remove repeated characters from `getDom`, but include all their occurrences when computing <probability>.
``
class DistFromString(s: String) extends FiniteDist[Char] {
require(s.nonEmpty)
private val chars = s.toList
private val dom = chars.distinct
def getDom: List[Char] = dom
def getProb(x: Char): Double =
chars.count(c => c == x).toDouble / chars.length.toDouble
}
``
The <probability mass function> is an <empirical probability distribution>:
$$
\boxed{p(c)=\frac{\#\{i:s_i=c\}}{|s|}.}
$$
Every character occurrence contributes exactly once to the total count, so the <probabilities> sum to one. Absent characters have count zero. For `"Scala"`, the support is `List('S','c','a','l')`, with <probabilities> $1/5,1/5,2/5,1/5$ respectively. Here `Char` means the language's UTF-16 code unit, matching the supplied interface rather than assuming one <Unicode> code point per element.
Back to article page