Skip to content

Instantly share code, notes, and snippets.

@ggramaize
Created February 5, 2021 12:18
Show Gist options
  • Save ggramaize/9670c226455a59e60e33b3c9b9641d2d to your computer and use it in GitHub Desktop.
Save ggramaize/9670c226455a59e60e33b3c9b9641d2d to your computer and use it in GitHub Desktop.
@Al_Grigor's challenge
<?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