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

1 Answer

0 votes
import java.util.Scanner;

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

public class TrigramGenerator {

    /**
        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 substring() to extract each 3‑character sequence.

        The algorithm is efficient: O(n) time, O(n) space.
    */
    public static String[] makeTrigrams(String word) {
        if (word.length() < 3) {
            return new String[0]; // No trigrams possible
        }

        int count = word.length() - 2;
        String[] result = new String[count];

        for (int i = 0; i < count; i++) {
            result[i] = word.substring(i, i + 3);
        }

        return result;
    }

    /**
        Main program:
          - Read a word from the user.
          - Generate trigrams.
          - Print each trigram.
    */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a word: ");
        String input = scanner.nextLine();

        String[] trigrams = makeTrigrams(input);

        System.out.println("\nTrigrams:");
        for (String t : trigrams) {
            System.out.println(t);
        }

        scanner.close();
    }
}


/*
run:

Enter a word: computer

Trigrams:
com
omp
mpu
put
ute
ter

*/

 



answered Sep 9 by avibootz
...