Skip to content

Instantly share code, notes, and snippets.

@msonowal
Created June 1, 2022 16:38
Show Gist options
  • Save msonowal/482d4e1c2760487e83a6e379f48220bd to your computer and use it in GitHub Desktop.
Save msonowal/482d4e1c2760487e83a6e379f48220bd to your computer and use it in GitHub Desktop.
function getHighestConsecutiveRepeatedNumber(string $numberOrString) {
if (strlen($numberOrString) == 0) {
echo 'Please provide a valid value';
return;
}
$resultSet = [];
$previousResult = ['value' => null,];
for ($i = 0; $i < strlen($numberOrString); $i++){
$currentValue = $numberOrString[$i];
if ($previousResult['value'] == $currentValue) {
$previousResult['count']++;
} else {
unset($previousResult);
//clearing memory address to newly define a value for the result entry
$previousResult = ['value' => $currentValue, 'count' => 1];
$resultSet[] = &$previousResult;
//storing the reference so that in future we can easy reference to increase the counts
}
}
$highest = $resultSet[0];
foreach ($resultSet as $result) {
if ($result['count'] > $highest['count']) {
$highest = $result;
}
}
return str_repeat($highest['value'], $highest['count']);
}
//now we can call the function by passing string or number it will support both and will return the value
$theBigNumber = '121231213243454622222212667';
$number = getHighestConsecutiveRepeatedNumber($theBigNumber);
echo $number;
$theBigString = 'abcasjdhakjnfjkryfjsyyyyyyyyyyyjkasjfhdshfsdfsdfddddda';
$string = getHighestConsecutiveRepeatedNumber($theBigString);
echo $string;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment