How to generate all trigrams (3-character sequences) from a given word in Swift

1 Answer

0 votes
/*
    -------------------------------------------------------------------------
    What is a trigram?
    -------------------------------------------------------------------------
    A trigram is a sequence of exactly three consecutive characters taken
    from a word. To generate all trigrams, we slide a window of length 3
    across the string. Each step produces a new 3‑character slice.

    Example:
        Word: "magic"
        Trigrams: ["mag", "agi", "gic"]

    Trigrams are useful in text processing, search algorithms,
    and language modeling because they capture small structural patterns
    inside words.
*/

import Foundation

/*
    Function: makeTrigrams
    ----------------------
    Returns an array containing all trigrams of the given word.

    Steps:
      - If the word is shorter than 3 characters, return an empty array.
      - Otherwise, slide a window of size 3 across the word.
      - Use String slicing with index offsets to extract each 3‑character sequence.

    The algorithm runs in O(n) time and uses O(n) space.
*/
func makeTrigrams(_ word: String) -> [String] {
    guard word.count >= 3 else {
        return []   // No trigrams possible
    }

    let count = word.count - 2
    var result: [String] = []
    result.reserveCapacity(count)

    // Convert to array of characters for safe indexing
    let chars = Array(word)

    for i in 0..<count {
        let trigram = String(chars[i...i+2])
        result.append(trigram)
    }

    return result
}

/*
    Main program:
      - Read a word from the user.
      - Generate trigrams.
      - Print each trigram.
*/
print("Enter a word: ", terminator: "")
if let input = readLine()?.trimmingCharacters(in: .whitespacesAndNewlines) {
    let trigrams = makeTrigrams(input)

    print("\nTrigrams:")
    for t in trigrams {
        print(t)
    }
}


/*
run:

Enter a word: computer

Trigrams:
com
omp
mpu
put
ute
ter

*/

 



answered Sep 9 by avibootz

Related questions

...