using System;
class TrigramGenerator
{
/*
-------------------------------------------------------------------------
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.
*/
/*
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 runs in O(n) time and uses O(n) space.
*/
public static string[] MakeTrigrams(string word)
{
if (word.Length < 3) {
return Array.Empty<string>(); // 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, 3);
}
return result;
}
/*
Main program:
- Read a word from the user.
- Generate trigrams.
- Print each trigram.
*/
static void Main()
{
Console.Write("Enter a word: ");
string input = Console.ReadLine();
string[] trigrams = MakeTrigrams(input);
Console.WriteLine();
Console.WriteLine("Trigrams:");
foreach (string t in trigrams) {
Console.WriteLine(t);
}
}
}
/*
run:
Enter a word: computer
Trigrams:
com
omp
mpu
put
ute
ter
*/