Created
February 5, 2021 12:18
-
-
Save ggramaize/9670c226455a59e60e33b3c9b9641d2d to your computer and use it in GitHub Desktop.
@Al_Grigor's challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function process( $input) | |
{ | |
$result = '['; | |
$occurences = array(); | |
$occur_offset = -1; | |
$input_sz = strlen($input); | |
for( $i=0; $i < $input_sz; ++$i) | |
{ | |
if( $occur_offset < 0 || $occurences[$occur_offset]['char'] != $input[$i] ) | |
{ | |
++$occur_offset; | |
$occurences[$occur_offset]['char'] = $input[$i]; | |
$occurences[$occur_offset]['count'] = 1; | |
continue; | |
} | |
// Increment the occurence counter | |
++$occurences[$occur_offset]['count']; | |
} | |
$is_first_pair = true; | |
for( $i=0; $i<count($occurences); ++$i) | |
{ | |
if( !$is_first_pair ) | |
$result .= ','; | |
$result .= '("' . $occurences[$i]['char'] . '", ' . $occurences[$i]['count'] . ')'; | |
$is_first_pair = false; | |
} | |
$result .= ']'; | |
return $result; | |
} | |
echo( process("aaaabbbcca") ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment