Search code examples
regexvb.netvisual-studioanagram

Check if two strings are anagrams in VB


I'm making a little anagram solving game in VB and I'd like to verify that the given word fits the letters given. For example, the string eliter shouldn't match letter because t only appears once in the above string. I already have a check to determine if the submission is a word, but ideally, a check to make sure it fits the letters given would be wrapped around that statement.

Public Class Form1
Public Function GenerateRandomString(ByRef iLength As Integer) As String
    Dim rdm As New Random()
    Dim allowChrs() As Char = "ABCDEFGHIJKLOMNOPQRSTUVWXYZ".ToCharArray()
    Dim sResult As String = ""

    For i As Integer = 0 To iLength - 1
        sResult += allowChrs(rdm.Next(0, allowChrs.Length))
    Next

    Return sResult

End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    countdown.Enabled = True
    lbl_countdown.Text = "10"

    lbl_anagram.Text = GenerateRandomString(9)
End Sub

Private Sub countdown_Tick(sender As Object, e As EventArgs) Handles countdown.Tick
    lbl_countdown.Text -= 1
    If lbl_countdown.Text < 1 Then
        countdown.Enabled = False
        MsgBox("End of game")

        Dim wordList As HashSet(Of String) = New HashSet(Of String)(File.ReadAllLines("words_alpha.txt"))
        If Not wordList.Contains(TextBox1.Text.ToString()) Then
            MsgBox("Not found")
        Else
            MsgBox("Found")
        End If
    End If
End Sub
End Class

Note that this needs to be in VB and preferably requires no extra libraries, etc.

Also note that you don't have to use all the letter but can't use more than what's available!

Thanks in advance!


Solution

  • You just need to sort your string alphabetically and compare the sorted string. Two anagram will have the same string when the characters are sorted.

    Sub Main()
    
        Dim s As String = "betjwepfw"
    
        Console.WriteLine(s)
        Console.WriteLine(New String(s.OrderBy(Function(c) c).ToArray()))
        Console.ReadLine()
    
    End Sub