Jump to content

iteration algorithm : string representation


amalafrida

Recommended Posts

While I don't agree with the reasoning behind this, here's a function.

 

<?php
$string = 'aaaaaaabbbcccccccddddeeeeeeeeee';
function compactString($str){
$chars = array();
for($i=0; $i<strlen($str); $i++){
	$c = $str[$i];
	if(!isset($chars[$c])){
		$chars[$c] = 0;
	}
	$chars[$c]++;
}
$newStr = '';
foreach($chars AS $c=>$v){
	$newStr .= $v.$c;
}
return $newStr;
}

$newStr = compactString($string);
echo $newStr;
?>

 

Output:

7a3b7c4d10e

could you have a situation where a letter is repeated later in the string?

 

eg aaaaabbbccccccccddeeeeeeeeeeaaaaaaaaagggg

 

if that isthe case:

 

<?php
$str = 'aaaaabbbccccccccddeeeeeeeeeeaaaaaaaaagggg';
echo condenseStr($str);     // ===> 5a3b8c2d10e9a4g


function condenseStr($str) {
    $l = strlen($str);
    $j = '';
    $res = '';
    $k = 0;
    while ($i<$l) {
        if ($str[$i] != $j) {
            if ($j) {
                $res .= "$k$j";
            }
            $j = $str[$i];
            $k = 0;
        }
        ++$k;
        ++$i;
    }
    $res .= "$k$j";
    return $res;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.