How to display string letters sorted by frequency in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Text;

class LetterFrequency
{
    // Pair structure: (letter, frequency)
    struct Pair
    {
        public char Letter;
        public int Freq;

        public Pair(char letter, int freq) {
            Letter = letter;
            Freq = freq;
        }
    }

    // sortByFrequency — counts how often each letter appears and returns a sorted list
    static List<Pair> SortByFrequency(string s)
    {
        int[] freq = new int[26];  // frequency array for 26 lowercase letters

        // Iterate through the string and count only alphabetic characters
        foreach (char c in s) {
            if (char.IsLetter(c)) {
                freq[char.ToLower(c) - 'a']++;
            }
        }

        // Build a list of (letter, frequency) pairs
        List<Pair> result = new List<Pair>();
        for (int i = 0; i < 26; i++) {
            result.Add(new Pair((char)('a' + i), freq[i]));
        }

        // Sort pairs by frequency in descending order
        result.Sort((a, b) => b.Freq.CompareTo(a.Freq));

        return result;
    }

    // Build a string sorted by frequency: ddddddddddddccccccbbbbbaaaafffeehhgs
    static string BuildSortedString(List<Pair> sorted)
    {
        StringBuilder outStr = new StringBuilder();

        foreach (Pair p in sorted) {
            // append 'p.Letter' repeated p.Freq times
            if (p.Freq > 0) {
                outStr.Append(new string(p.Letter, p.Freq));
            }
        }

        return outStr.ToString();
    }

    static void Main()
    {
        // Input text to analyze
        string text = "bbcabddddccafffadbbcdccsedddddhhgade";

        // Get sorted frequency list
        List<Pair> sorted = SortByFrequency(text);

        // Print each letter and its frequency
        foreach (Pair p in sorted) {
            if (p.Freq != 0)
                Console.WriteLine($"{p.Letter}: {p.Freq}");
        }

        // Print the reconstructed sorted string
        string lettersSortedByFrequency = BuildSortedString(sorted);
        Console.WriteLine();
        Console.WriteLine("Sorted string: " + lettersSortedByFrequency);
    }
}


/*
run:

d: 12
c: 6
b: 5
a: 4
f: 3
e: 2
h: 2
g: 1
s: 1

Sorted string: ddddddddddddccccccbbbbbaaaafffeehhgs

*/

 



answered 2 days ago by avibootz
...