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
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>';
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.