How to get common letters that appear in every word in a list of words with VB.NET

1 Answer

0 votes
Imports System

Module CommonLettersProgram

    '
    ' Efficient algorithm using bitmasking:
    ' ------------------------------------
    ' Each letter 'a'..'z' is represented by one bit in a 32-bit Integer.
    '
    '     bit 0  -> 'a'
    '     bit 1  -> 'b'
    '     ...
    '     bit 25 -> 'z'
    '
    ' For each word:
    '     - Set the bit corresponding to each letter.
    ' Then:
    '     - Intersect all bitmasks using bitwise AND.
    ' The remaining bits represent letters common to all words.
    '
    ' This avoids sorting, dynamic memory, and repeated scanning.
    '

    ' Convert a word into a bitmask of its letters
    Function WordToMask(word As String) As Integer
        Dim mask As Integer = 0

        For Each c As Char In word
            If c >= "a"c AndAlso c <= "z"c Then
                mask = mask Or (1 << (Convert.ToInt32(c) - Convert.ToInt32("a"c)))   ' set bit for this letter
            End If
        Next

        Return mask
    End Function

    ' Compute common letters across all words
    Function CommonLetters(words As String()) As Integer
        If words.Length = 0 Then Return 0

        Dim common As Integer = WordToMask(words(0))

        For i As Integer = 1 To words.Length - 1
            common = common And WordToMask(words(i))   ' bitwise intersection
        Next

        Return common
    End Function

    ' Print letters represented by a bitmask
    Sub PrintMaskLetters(mask As Integer)
        For i As Integer = 0 To 25
            If (mask And (1 << i)) <> 0 Then
                Console.Write(Convert.ToChar(Convert.ToInt32("a"c) + i) & " ")
            End If
        Next
        Console.WriteLine()
    End Sub

    Sub Main()
        Dim words As String() = {
            "algebraic",
            "alphabetic",
            "ambiance",
            "abacus",
            "metabolic",
            "parabolic",
            "playback",
            "drawback",
            "fabricate",
            "flashback",
            "syllabic"
        }

        Dim resultMask As Integer = CommonLetters(words)

        Console.WriteLine("Common letters across all words:")
        PrintMaskLetters(resultMask)
    End Sub

End Module



'
' run:
'
' Common letters across all words:
' a b c
'

 



answered 4 hours ago by avibootz

Related questions

...