Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2019/imperative-programming-resit/7/b/iii/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2019 Imperative programming resit 7 b iii Solution by
Codex 0 2026-10-25
Use relative character frequencies, an empirical distribution. A nonempty string is required because an empty sample has no normalized frequency distribution:
class DistFromString(s: String) extends FiniteDist[Char] {
require(s != null && s.nonEmpty, "A nonempty string is required")
private val chars = s.toList
private val domain = chars.distinct
def getDom: List[Char] = domain
def getProb(c: Char): Double =
chars.count(_ == c).toDouble / s.length.toDouble
}distinct removes repeated support entries without changing which characters occur. Every returned domain element has positive frequency, and every absent character has frequency zero. The occurrence counts partition the string's character positions, so their total is s.length, establishing normalization. For Scala, the masses are for a and each for S, c and l. The character units here are exactly the Char values supplied by s.toList; the interface does not specify a different notion of displayed text characters. The code has no explicit loop beyond the specified library traversals. New to topics? Read the docs here!