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

1 Answer

0 votes
Imports System

Module 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.
    '---------------------------------------------------------------------------
    Function MakeTrigrams(word As String) As String()
        If word.Length < 3 Then
            Return Array.Empty(Of String)()
        End If

        Dim count As Integer = word.Length - 2
        Dim result(count - 1) As String

        For i As Integer = 0 To count - 1
            result(i) = word.Substring(i, 3)
        Next

        Return result
    End Function

    '---------------------------------------------------------------------------
    ' Main program:
    '   - Read a word from the user.
    '   - Generate trigrams.
    '   - Print each trigram.
    '---------------------------------------------------------------------------
    Sub Main()
        Console.Write("Enter a word: ")
        Dim input As String = Console.ReadLine()

        Dim trigrams As String() = MakeTrigrams(input)

        Console.WriteLine()
        Console.WriteLine("Trigrams:")

        For Each t In trigrams
            Console.WriteLine(t)
        Next
    End Sub

End Module


'
' run:
'
' Enter a word: computer
'
' Trigrams:
' com
' omp
' mpu
' put
' ute
' ter
'

 



answered Sep 9 by avibootz
edited Sep 9 by avibootz
...