amalafrida Posted June 8, 2012 Share Posted June 8, 2012 what would be the best way to generate this string 7a3b7c4d10e from this string aaaaaaabbbcccccccddddeeeeeeeeee I have many 10,000s of strings of this sort, 168 characters each to store in database. attempting to minimize storage space. ??? thanks in advance Link to comment https://forums.phpfreaks.com/topic/263877-iteration-algorithm-string-representation/ Share on other sites More sharing options...
Jessica Posted June 8, 2012 Share Posted June 8, 2012 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 Link to comment https://forums.phpfreaks.com/topic/263877-iteration-algorithm-string-representation/#findComment-1352257 Share on other sites More sharing options...
Barand Posted June 8, 2012 Share Posted June 8, 2012 could you have a situation where a letter is repeated later in the string? eg aaaaabbbccccccccddeeeeeeeeeeaaaaaaaaagggg Link to comment https://forums.phpfreaks.com/topic/263877-iteration-algorithm-string-representation/#findComment-1352316 Share on other sites More sharing options...
requinix Posted June 8, 2012 Share Posted June 8, 2012 Are you basically just counting characters? We need to know more. Link to comment https://forums.phpfreaks.com/topic/263877-iteration-algorithm-string-representation/#findComment-1352320 Share on other sites More sharing options...
Barand Posted June 8, 2012 Share Posted June 8, 2012 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; } ?> Link to comment https://forums.phpfreaks.com/topic/263877-iteration-algorithm-string-representation/#findComment-1352322 Share on other sites More sharing options...
amalafrida Posted June 11, 2012 Author Share Posted June 11, 2012 Yes, a letter can repeat. Am interested in elaboration of this observation by Jesirose: "While I don't agree with the reasoning behind this, here's a function." And yes, just counting characters. Thanks for all the help. Link to comment https://forums.phpfreaks.com/topic/263877-iteration-algorithm-string-representation/#findComment-1352905 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.