Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
' Groups a list of strings into sublists of anagrams.
Function GroupAnagrams(words As List(Of String)) As List(Of List(Of String))
If words Is Nothing Then
Throw New ArgumentException("Input must be a list of strings.")
End If
Dim map As New Dictionary(Of String, List(Of String))()
For Each word In words
If word Is Nothing Then
Throw New ArgumentException("All elements in the list must be non-null strings.")
End If
' Sort characters
Dim chars As Char() = word.ToCharArray()
Array.Sort(chars)
Dim sorted As String = New String(chars)
' Group words by their sorted key
If Not map.ContainsKey(sorted) Then
map(sorted) = New List(Of String)()
End If
map(sorted).Add(word)
Next
' Return grouped anagrams as a list of lists
Return map.Values.ToList()
End Function
Sub Main()
Try
Dim lst As New List(Of String) From {"eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"}
Dim result As List(Of List(Of String)) = GroupAnagrams(lst)
' Print result
Console.WriteLine("[")
For Each group In result
Console.Write(" [ ")
For i As Integer = 0 To group.Count - 1
Console.Write("'" & group(i) & "'")
If i < group.Count - 1 Then
Console.Write(", ")
End If
Next
Console.WriteLine(" ]")
Next
Console.WriteLine("]")
Catch ex As Exception
Console.Error.WriteLine(ex.Message)
End Try
End Sub
End Module
' run:
'
' [
' [ 'eat', 'tea', 'ate' ]
' [ 'rop', 'orp', 'pro' ]
' [ 'nat', 'tan' ]
' [ 'bat' ]
' ]
'