Imports System
Imports System.Collections.Generic
Imports System.Text
Module LetterFrequency
' Pair structure: (letter, frequency)
Structure Pair
Public Letter As Char
Public Freq As Integer
Public Sub New(letter As Char, freq As Integer)
Me.Letter = letter
Me.Freq = freq
End Sub
End Structure
' sortByFrequency — counts how often each letter appears and returns a sorted list
Function SortByFrequency(s As String) As List(Of Pair)
Dim freq(25) As Integer ' frequency array for 26 lowercase letters
' Iterate through the string and count only alphabetic characters
For Each c As Char In s
If Char.IsLetter(c) Then
freq(Convert.ToInt32(Char.ToLower(c)) - Convert.ToInt32("a"c)) += 1
End If
Next
' Build a list of (letter, frequency) pairs
Dim result As New List(Of Pair)
For i As Integer = 0 To 25
result.Add(New Pair(Convert.ToChar(Convert.ToInt32("a"c) + i), freq(i)))
Next
' Sort pairs by frequency in descending order
result.Sort(Function(a, b) b.Freq.CompareTo(a.Freq))
Return result
End Function
' Build a string sorted by frequency: ddddddddddddccccccbbbbbaaaafffeehhgs
Function BuildSortedString(sorted As List(Of Pair)) As String
Dim out As New StringBuilder()
For Each p As Pair In sorted
' append 'p.Letter' repeated p.Freq times
If p.Freq > 0 Then
out.Append(New String(p.Letter, p.Freq))
End If
Next
Return out.ToString()
End Function
Sub Main()
' Input text to analyze
Dim text As String = "bbcabddddccafffadbbcdccsedddddhhgade"
' Get sorted frequency list
Dim sorted As List(Of Pair) = SortByFrequency(text)
' Print each letter and its frequency
For Each p As Pair In sorted
If p.Freq <> 0 Then
Console.WriteLine($"{p.Letter}: {p.Freq}")
End If
Next
' Print the reconstructed sorted string
Dim lettersSortedByFrequency As String = BuildSortedString(sorted)
Console.WriteLine()
Console.WriteLine("Sorted string: " & lettersSortedByFrequency)
End Sub
End Module
' run:
'
' d: 12
' c: 6
' b: 5
' a: 4
' f: 3
' e: 2
' h: 2
' g: 1
' s: 1
'
' Sorted string: ddddddddddddccccccbbbbbaaaafffeehhgs
'