Jump to content

[SOLVED] add missing values


The Little Guy

Recommended Posts

say I have this: (5+5

 

I have code that will add on the last parenthesis to that, but it doesn't work. It works if there is at least one parenthesis on each side then it works, so these work:

 

(5+5))

(5+5)+5)

((5+5)+5

 

 

but the top one doesn't

 

    $clp = substr_count($calc,'(');
    $crp = substr_count($calc,')');
    echo '<h1>Uneven parenthesis count</h1>';
    if($clp > $crp){
        $f = '';
        for($cc = $clp - $crp;$cc<$clp;$cc++){
            $f .= ')';
        }
        $nCalc = $calc.$f;
    }elseif($clp < $crp){
        $f = '';
        for($cc = $crp - $clp;$cc<$crp;$cc++){
            $f .= '(';
        }
        $nCalc = $f.$calc;
    }

Link to comment
https://forums.phpfreaks.com/topic/129261-solved-add-missing-values/
Share on other sites

yeah, looking at it again, the logic was off a little. try this out (i removed the IF statements since they aren't needed):

<?php
$cases = array(
  '5+5)',
  '(5+5))',
  '(5+5)+5)',
  '((5+5)+5',
);
print '<table border="1">';
foreach($cases as $calc){
  $clp = substr_count($calc,'(');
  $crp = substr_count($calc,')');
  $nCalc = $calc;
  for($cc = $clp - $crp;$cc > 0;$cc--){
    $nCalc .= ')';
  }
  for($cc = $crp - $clp;$cc > 0;$cc--){
    $nCalc = '('.$nCalc;
  }
  print '<tr><td>'.$calc.'</td><td>'.$nCalc.'</td></tr>';
}
print '</table>';
?>

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.