Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

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

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.
*/

use std::io::{self, Write};

/*
    Function: make_trigrams
    -----------------------
    Returns a vector containing all trigrams of the given word.

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

    The algorithm runs in O(n) time and uses O(n) space.

    Note:
      Rust strings are UTF‑8, so slicing must be done on byte indices.
      This function assumes ASCII input for simplicity.
*/
fn make_trigrams(word: &str) -> Vec<String> {
    if word.len() < 3 {
        return Vec::new();
    }

    let count = word.len() - 2;
    let mut result: Vec<String> = Vec::with_capacity(count);

    for i in 0..count {
        result.push(word[i..i + 3].to_string());
    }

    result
}

/*
    Main program:
      - Read a word from the user.
      - Generate trigrams.
      - Print each trigram.
*/
fn main() {
    print!("Enter a word: ");
    io::stdout().flush().unwrap();

    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();

    let word = input.trim();
    let trigrams = make_trigrams(word);

    println!("\nTrigrams:");
    for t in trigrams {
        println!("{}", t);
    }
}


/*
run:

Enter a word: computer

Trigrams:
com
omp
mpu
put
ute
ter

*/

 



answered Sep 9 by avibootz

Related questions

...