Created
January 25, 2023 20:08
-
-
Save rudwolf/0050bb6bd86d00218d6f4e90a34c6a98 to your computer and use it in GitHub Desktop.
Coding test for rightbalance
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 | |
/* | |
Let’s say we are dealing with sending data over the internet, to make it simple, assume this plain text, in order to save some bandwidth we want to compress it, according to the following function: | |
compress(aaaaca) -> ax4ca | |
compress(aaaaaabbbcaaa) -> ax6bx3cax3 | |
compress(mississippi) -> misx2isx2ipx2i | |
*/ | |
function compress($string) | |
{ | |
$letters = str_split($string); | |
$output = ''; | |
$letter_count = 1; | |
foreach ($letters as $key => $letter) { | |
$next_letter = $letters[$key+1]; | |
if ($letter == $next_letter) { | |
$letter_count++; | |
} else { | |
if ($letter_count > 1) { | |
$output .= $letter.'x'.$letter_count; | |
} else { | |
$output .= $letter; | |
} | |
$letter_count = 1; | |
} | |
} | |
return $output; | |
} | |
$tests = array( | |
[ | |
'test' => 'aaaaca', | |
'expected' => 'ax4ca', | |
], | |
[ | |
'test' => 'aaaaaabbbcaaa', | |
'expected' => 'ax6bx3cax3', | |
], | |
[ | |
'test' => 'mississippi', | |
'expected' => 'misx2isx2ipx2i', | |
], | |
); | |
foreach ($tests as $key => $test) { | |
$result = compress($test['test']); | |
echo ($result == $test['expected']) ? "valid! compress(".$test['test'].") == ".$test['expected'] : "wrong! shoud be...".$test['expected']; | |
echo '<br>'; | |
echo "result: $result"; | |
echo '<br><br>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment