Last active
June 13, 2019 10:59
-
-
Save ashbeats/ffded4265520f998d99b2793e59766a4 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Author: git@ashbeats | |
* Date: 6/12/2019 | |
* Time: 10:46 PM | |
*/ | |
$testCases = [ | |
'123Adggaaabaaaaaaabbc' => 'a', | |
'aaabbb' => 'a', // a | |
'baaabbb' => 'b', // b | |
'baaa1111111111bbb' => '1', // 1 | |
'baaa1111111111bbb-----------------' => '1', // 1 | |
'baa##a11111111^^11bbb' => '1', // 1 | |
'baa##a1111 1111^^11bbb' => '1', // 1 | |
'ជុន ចាន់បុត្រ apple អ្នកវិភាគដ៏ឆ្នើម ដែលគួរចង់ស្ដាប់' => 'p', // p | |
]; | |
/** | |
* Simple way to solve it. | |
* | |
* @param $string | |
* | |
* @return mixed | |
*/ | |
function method_1(string $string): string | |
{ | |
preg_match_all( '/[a-zA-Z0-9]/i', $string, $results, PREG_PATTERN_ORDER ); | |
$counts = array_count_values( $results[ 0 ] ); | |
$max = 0; | |
foreach ( $counts as $char => $seen ) { | |
$max = ( $seen > $max ) ? $seen : $max; | |
} | |
return array_search( $max, $counts, true ); | |
} | |
/*** | |
* This is the shortest version for now in php... | |
* | |
* @param $string | |
* | |
* @return mixed | |
*/ | |
function method_2(string $string): string | |
{ | |
preg_match_all( '/[a-zA-Z0-9]/i', $string, $results, PREG_PATTERN_ORDER ); | |
$counts = array_count_values( $results[ 0 ] ); | |
return array_search( | |
max( array_values( $counts ) ), | |
$counts, | |
true | |
); | |
} | |
/****** | |
* Run the tests below. | |
*/ | |
$passed = true; | |
foreach ( $testCases as $seed => $expected ) { | |
$a = method_1( $seed ); | |
$b = method_2( $seed ); | |
if ( $a !== $b ) { | |
echo "Both methods yielded different results. Hmm... \n"; | |
} | |
if ( $a !== $expected ) { | |
$passed = false; | |
echo " ✘ Failed for seed: $seed\n"; | |
echo "\t - Expected was: $expected\n"; | |
echo "method_1 failed. Returned ($a) \n"; | |
break; | |
} | |
if ( $b !== $expected ) { | |
$passed = false; | |
echo " ✘ Failed for seed: $seed\n"; | |
echo "\t - Expected was: $expected\n"; | |
echo "method_2 failed. Returned ($b) \n"; | |
break; | |
} | |
} | |
if ( $passed ) { | |
echo "\n ✔ All tests passed!\n\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment