// sortByFrequency — counts how often each letter appears and returns a sorted list
function sortByFrequency(string $s): array {
// Create a frequency array for 26 lowercase letters, initialized to 0
$freq = array_fill(0, 26, 0);
// Iterate through the string and count only alphabetic characters
foreach (str_split($s) as $c) {
if (ctype_alpha($c)) {
// Convert to lowercase and map 'a'..'z' to 0..25
$freq[ord(strtolower($c)) - ord('a')]++;
}
}
// Build an array of (letter, frequency) pairs
$result = [];
for ($i = 0; $i < 26; $i++) {
$result[] = [
'letter' => chr(ord('a') + $i),
'freq' => $freq[$i]
];
}
// Sort pairs by frequency in descending order
usort($result, function($a, $b) {
return $b['freq'] <=> $a['freq']; // spaceship operator
});
return $result;
}
// Build a string sorted by frequency: ddddddddddddccccccbbbbbaaaafffeehhgs
function buildSortedString(array $sorted): string {
$out = '';
foreach ($sorted as $p) {
// append 'p["letter"]' repeated p["freq"] times
if ($p['freq'] > 0) {
$out .= str_repeat($p['letter'], $p['freq']);
}
}
return $out;
}
// Input text to analyze
$text = "bbcabddddccafffadbbcdccsedddddhhgade";
// Get sorted frequency list
$sorted = sortByFrequency($text);
// Print each letter and its frequency
foreach ($sorted as $p) {
if ($p['freq'] != 0) {
echo $p['letter'] . ": " . $p['freq'] . PHP_EOL;
}
}
// Print the reconstructed sorted string
$letters_sorted_by_frequency = buildSortedString($sorted);
echo PHP_EOL . "Sorted string: " . $letters_sorted_by_frequency . PHP_EOL;
/*
run:
d: 12
c: 6
b: 5
a: 4
f: 3
e: 2
h: 2
g: 1
s: 1
Sorted string: ddddddddddddccccccbbbbbaaaafffeehhgs
*/