How to display string letters sorted by frequency in TypeScript

1 Answer

0 votes
// Pair structure: (letter, frequency)
interface Pair {
    letter: string;
    freq: number;
}

// sortByFrequency — counts how often each letter appears and returns a sorted list
function sortByFrequency(text: string): Pair[] {
    // Create a frequency array for 26 lowercase letters, initialized to 0
    const freq: number[] = Array(26).fill(0);

    // Iterate through the string and count only alphabetic characters
    for (const ch of text) {
        if (/[a-zA-Z]/.test(ch)) {
            const lower: string = ch.toLowerCase();
            const index: number = lower.charCodeAt(0) - "a".charCodeAt(0);
            freq[index]++;
        }
    }

    // Build an array of (letter, frequency) pairs
    const result: Pair[] = [];
    for (let i = 0; i < 26; i++) {
        const letter: string = String.fromCharCode("a".charCodeAt(0) + i);
        result.push({ letter, freq: freq[i] });
    }

    // Sort pairs by frequency in descending order
    result.sort((a: Pair, b: Pair) => b.freq - a.freq);

    return result;
}

// Build a string sorted by frequency: ddddddddddddccccccbbbbbaaaafffeehhgs
function buildSortedString(sorted: Pair[]): string {
    let output: string = "";

    for (const p of sorted) {
        // append 'p.letter' repeated p.freq times
        if (p.freq > 0) {
            output += p.letter.repeat(p.freq);
        }
    }

    return output;
}

// Main logic
function main(): void {
    // Input text to analyze
    const text: string = "bbcabddddccafffadbbcdccsedddddhhgade";

    // Get sorted frequency list
    const sorted: Pair[] = sortByFrequency(text);

    // Print each letter and its frequency
    for (const p of sorted) {
        if (p.freq !== 0) {
            console.log(`${p.letter}: ${p.freq}`);
        }
    }

    // Print the reconstructed sorted string
    const lettersSortedByFrequency: string = buildSortedString(sorted);
    console.log("\nSorted string:", lettersSortedByFrequency);
}

main();


/*
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

Related questions

...