// Cats: a typing test, in Swift. A project for cs.dorian.page's Swift // tutorial, after CS61A's "Computer Aided Typing Software" (UC Berkeley). // // Run the tests: swift cats.swift test // Run one problem: swift cats.swift test 6 // Take a typing test: swift cats.swift type // // Write your code between each `BEGIN PROBLEM` and `END PROBLEM` line. // Everything else is provided; read it, but do not change it. // MARK: - Provided: text utilities /// Lowercase letters, digits, and spaces only; everything else is removed. func removePunctuation(_ text: String) -> String { String(text.filter { $0.isLetter || $0.isNumber || $0 == " " }) } /// Split text on spaces, dropping empty pieces. func words(_ text: String) -> [String] { text.split(separator: " ").map(String.init) } /// A difference function measures how far `start` is from `goal`. It may /// stop early and return any value above `limit` once the answer is known to /// be too large. typealias DiffFunction = (_ start: String, _ goal: String, _ limit: Int) -> Int /// A match records the words in a race and, for each player, how long each /// word took them (in seconds). struct Match { let words: [String] let times: [[Int]] } let samplePassages = [ "Cute cats nap in the sun.", "Dogs dig holes, and cats watch them do it.", "A typing test measures speed and accuracy.", "Swift runs on the server, too.", ] let dictionary = ["and", "animal", "cat", "cats", "code", "coat", "dog", "hello", "help", "kitten", "program", "swift", "test", "the", "then", "they", "type", "typing", "water", "word", "words", "world"] // MARK: - Phase 1: Typing // BEGIN PROBLEM 1 /// The `k`th passage (counting from 0) for which `select` is true, or "" /// if there are not that many. func pick(_ passages: [String], select: (String) -> Bool, k: Int) -> String { return "" // Replace this line. } // END PROBLEM 1 // BEGIN PROBLEM 2 /// A selector that is true for passages containing any of the `topic` /// words, ignoring case and punctuation. Whole words only. func about(_ topic: [String]) -> (String) -> Bool { return { _ in false } // Replace this line. } // END PROBLEM 2 // BEGIN PROBLEM 3 /// The percentage of words in `typed` that match the word at the same /// position in `source`. Both empty is 100; exactly one empty is 0. func accuracy(typed: String, source: String) -> Double { return 0 // Replace this line. } // END PROBLEM 3 // BEGIN PROBLEM 4 /// Words per minute, counting every five characters as one word. func wpm(typed: String, elapsed seconds: Double) -> Double { precondition(seconds > 0, "elapsed time must be positive") return 0 // Replace this line. } // END PROBLEM 4 // MARK: - Phase 2: Autocorrect // BEGIN PROBLEM 5 /// If `typed` is in `wordList`, return it. Otherwise return the word in /// `wordList` with the smallest difference from `typed` (the earliest one on /// a tie), unless that difference is greater than `limit`, in which case /// return `typed` unchanged. func autocorrect(_ typed: String, wordList: [String], diff: DiffFunction, limit: Int) -> String { return typed // Replace this line. } // END PROBLEM 5 // BEGIN PROBLEM 6 /// The number of positions where the two strings differ, plus the difference /// in their lengths. Recursive, no loops; stop once the count exceeds `limit`. func furryFixes(_ start: String, _ goal: String, _ limit: Int) -> Int { return 0 // Replace this line. } // END PROBLEM 6 // BEGIN PROBLEM 7 /// The fewest single-character additions, removals, and substitutions that /// turn `start` into `goal`. Recursive; stop once the count exceeds `limit`. func minimumMewtations(_ start: String, _ goal: String, _ limit: Int) -> Int { return 0 // Replace this line. } // END PROBLEM 7 // MARK: - Phase 3: Multiplayer // BEGIN PROBLEM 8 /// Send this player's progress through `upload` and return it. Progress is /// the fraction of the prompt's words typed correctly, counting only up to /// the first mistake. func reportProgress(typed: [String], prompt: [String], playerID: Int, upload: (_ playerID: Int, _ progress: Double) -> Void) -> Double { return 0 // Replace this line. } // END PROBLEM 8 // BEGIN PROBLEM 9 /// Build a Match from each player's timestamps. `timestamps[p]` holds the /// moment player p started, then the moment they finished each word, so /// each word's time is the difference between consecutive timestamps. func timePerWord(_ words: [String], timestamps: [[Int]]) -> Match { return Match(words: words, times: []) // Replace this line. } // END PROBLEM 9 // BEGIN PROBLEM 10 /// For each player, the words they typed faster than every other player, in /// order. A tie goes to the player with the smaller number. func fastestWords(_ match: Match) -> [[String]] { return [] // Replace this line. } // END PROBLEM 10 // MARK: - Tests (do not edit below this line) var onlyProblem: Int? = nil var passed = 0 var failed = 0 var failedProblems = Set() func check(_ problem: Int, _ description: String, _ actual: @autoclosure () -> T, _ expected: T) { if let only = onlyProblem, only != problem { return } let value = actual() if value == expected { passed += 1 } else { failed += 1 failedProblems.insert(problem) print("✗ Problem \(problem): \(description)") print(" expected \(expected), got \(value)") } } func close(_ a: Double, _ b: Double) -> Bool { abs(a - b) < 1e-9 } func runTests() { // Problem 1: pick let passages = ["short one", "a longer passage here", "tiny", "another long passage"] let isLong: (String) -> Bool = { $0.count > 10 } check(1, "first long passage", pick(passages, select: isLong, k: 0), "a longer passage here") check(1, "second long passage", pick(passages, select: isLong, k: 1), "another long passage") check(1, "not enough passages", pick(passages, select: isLong, k: 2), "") check(1, "select everything", pick(passages, select: { _ in true }, k: 2), "tiny") // Problem 2: about let aboutCats = about(["cat", "dog"]) check(2, "matches a whole word", aboutCats("Cute cats nap in the sun."), false) check(2, "ignores case and punctuation", aboutCats("My Dog! It runs."), true) check(2, "whole words only", aboutCats("Concatenate these."), false) check(2, "topic words are case-insensitive", about(["SWIFT"])("Swift runs on the server, too."), true) check(2, "works with pick", pick(samplePassages, select: about(["cats"]), k: 1), "Dogs dig holes, and cats watch them do it.") // Problem 3: accuracy check(3, "all correct", close(accuracy(typed: "Cute cats nap", source: "Cute cats nap"), 100), true) check(3, "half correct", close(accuracy(typed: "Cute dogs nap now", source: "Cute cats nap in"), 50), true) check(3, "typed more than the source", close(accuracy(typed: "a b c d", source: "a b"), 50), true) check(3, "typed less than the source", close(accuracy(typed: "a", source: "a b c"), 100), true) check(3, "both empty", close(accuracy(typed: "", source: ""), 100), true) check(3, "nothing typed", close(accuracy(typed: "", source: "a"), 0), true) check(3, "case matters", close(accuracy(typed: "cute", source: "Cute"), 0), true) // Problem 4: wpm check(4, "25 characters in 30 seconds", close(wpm(typed: "hello friend hello buddy!", elapsed: 30), 10), true) check(4, "empty text", close(wpm(typed: "", elapsed: 10), 0), true) check(4, "one minute", close(wpm(typed: String(repeating: "a", count: 100), elapsed: 60), 20), true) // Problem 5: autocorrect let byLength: DiffFunction = { start, goal, _ in abs(start.count - goal.count) } check(5, "already a word", autocorrect("cat", wordList: ["cat", "dog"], diff: byLength, limit: 10), "cat") check(5, "closest by the difference function", autocorrect("hello", wordList: ["hi", "house", "hey"], diff: byLength, limit: 10), "house") check(5, "ties go to the earliest word", autocorrect("abcd", wordList: ["ab", "abcde", "abcdef"], diff: byLength, limit: 10), "abcde") check(5, "too far away", autocorrect("tosting", wordList: ["testing", "asking", "fasting"], diff: { _, _, _ in 6 }, limit: 5), "tosting") check(5, "exactly at the limit", autocorrect("a", wordList: ["abc"], diff: byLength, limit: 2), "abc") // Problem 6: furryFixes check(6, "one substitution", furryFixes("nice", "rice", 10), 1) check(6, "same length", furryFixes("range", "rungs", 100), 2) check(6, "different lengths", furryFixes("pill", "pillage", 10), 3) check(6, "both differ", furryFixes("roses", "arose", 100), 5) check(6, "empty", furryFixes("", "abc", 5), 3) check(6, "result above the limit", furryFixes("abcdef", "uvwxyz", 2) > 2, true) // Problem 7: minimumMewtations check(7, "add and remove", minimumMewtations("ckiteus", "kittens", 100), 3) check(7, "one addition", minimumMewtations("cat", "cats", 100), 1) check(7, "one removal", minimumMewtations("hello", "hell", 100), 1) check(7, "substitutions", minimumMewtations("kitten", "sitting", 100), 3) check(7, "empty", minimumMewtations("", "word", 100), 4) check(7, "same", minimumMewtations("swift", "swift", 0), 0) check(7, "above the limit", minimumMewtations("salamander", "mandolin", 2) > 2, true) check(7, "stops early (this should finish instantly)", minimumMewtations("abcdefghijklmnop", "zyxwvutsrqponmlk", 3) > 3, true) check(7, "autocorrect with edit distance", autocorrect("typng", wordList: dictionary, diff: minimumMewtations, limit: 2), "typing") check(7, "one missing letter", autocorrect("kiten", wordList: dictionary, diff: minimumMewtations, limit: 1), "kitten") check(7, "autocorrect keeps unknown far words", autocorrect("zzzzzz", wordList: dictionary, diff: minimumMewtations, limit: 2), "zzzzzz") // Problem 8: reportProgress check(8, "progress up to the first mistake", { var uploads: [String] = [] let progress = reportProgress(typed: ["I", "have", "begun"], prompt: ["I", "have", "begun", "to", "type"], playerID: 3) { id, value in uploads.append("\(id):\(value)") } return [String(progress)] + uploads }(), ["0.6", "3:0.6"]) check(8, "a mistake stops the count", reportProgress(typed: ["I", "hve", "begun"], prompt: ["I", "have", "begun", "now"], playerID: 1) { _, _ in }, 0.25) check(8, "finished", reportProgress(typed: ["a", "b"], prompt: ["a", "b"], playerID: 0) { _, _ in }, 1.0) // Problem 9: timePerWord let match = timePerWord(["What", "great", "luck"], timestamps: [[0, 2, 3, 5], [0, 1, 6, 9]]) check(9, "keeps the words", match.words, ["What", "great", "luck"]) check(9, "differences between timestamps", match.times, [[2, 1, 2], [1, 5, 3]]) check(9, "a later start", timePerWord(["a"], timestamps: [[10, 13]]).times, [[3]]) // Problem 10: fastestWords check(10, "each player's fastest words", fastestWords(match), [["great", "luck"], ["What"]]) check(10, "ties go to the earlier player", fastestWords(Match(words: ["a", "b"], times: [[1, 2], [1, 1]])), [["a"], ["b"]]) check(10, "three players", fastestWords(Match(words: ["x", "y", "z"], times: [[5, 5, 5], [4, 6, 5], [6, 4, 1]])), [[], ["x"], ["y", "z"]]) let total = passed + failed if failed == 0 && total > 0 { print("\(total) of \(total) checks passed.") print(onlyProblem.map { "Problem \($0) passed." } ?? "All tests passed.") } else { print("\(passed) of \(total) checks passed. Problems to revisit: \(failedProblems.sorted()).") } } /// A typing test in the terminal, using your functions. func typingTest() { let passage = pick(samplePassages, select: { _ in true }, k: Int.random(in: 0..