Determine if a string is collapsible: Difference between revisions

No edit summary
Line 783:
</pre>
 
=={{header|PHP}}==
 
<lang PHP><?php
 
function collapseString($string) {
$previousChar = null;
$collapse = '';
$charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
for ($i = 0 ; $i < count($charArray) ; $i++) {
$currentChar = $charArray[$i];
if ($previousChar !== $currentChar) {
$collapse .= $charArray[$i];
}
$previousChar = $currentChar;
}
return $collapse;
}
 
function isCollapsible($string) {
return ($string !== collapseString($string));
}
 
$strings = array(
'',
'another non colapsing string',
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
'..1111111111111111111111111111111111111111111111111111111111111117777888',
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
' --- Harry S Truman ',
'0112223333444445555556666666777777778888888889999999999',
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
'headmistressship',
"😍😀🙌💃😍😍😍🙌",
);
 
foreach ($strings as $original) {
echo 'Original : <<<', $original, '>>> (len=', mb_strlen($original), ')', PHP_EOL;
if (isCollapsible($original)) {
$collapse = collapseString($original);
echo 'Collapse : <<<', $collapse, '>>> (len=', mb_strlen($collapse), ')', PHP_EOL, PHP_EOL;
} else {
echo 'Collapse : string is not collapsing...', PHP_EOL, PHP_EOL;
}
}</lang>
 
{{out}}
<pre>Original : <<<>>> (len=0)
Collapse : string is not collapsing...
 
Original : <<<another non colapsing string>>> (len=28)
Collapse : string is not collapsing...
 
Original : <<<"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln >>> (len=72)
Collapse : <<<"If I were two-faced, would I be wearing this one?" - Abraham Lincoln >>> (len=70)
 
Original : <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>> (len=72)
Collapse : <<<.178>>> (len=4)
 
Original : <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>> (len=72)
Collapse : <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>> (len=69)
 
Original : <<< --- Harry S Truman >>> (len=72)
Collapse : <<< - Hary S Truman >>> (len=17)
 
Original : <<<0112223333444445555556666666777777778888888889999999999>>> (len=55)
Collapse : <<<0123456789>>> (len=10)
 
Original : <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>> (len=80)
Collapse : <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>> (len=77)
 
Original : <<<headmistressship>>> (len=16)
Collapse : <<<headmistreship>>> (len=14)
 
Original : <<<😍😀🙌💃😍😍😍🙌>>> (len=8)
Collapse : <<<😍😀🙌💃😍🙌>>> (len=6)</pre>
 
=={{header|Python}}==
Anonymous user