The Little Guy Posted October 20, 2008 Share Posted October 20, 2008 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; } Quote Link to comment Share on other sites More sharing options...
rhodesa Posted October 20, 2008 Share Posted October 20, 2008 it should be <= on both: for($cc = $clp - $crp;$cc<=$clp;$cc++){ ... for($cc = $crp - $clp;$cc<=$crp;$cc++){ Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted October 20, 2008 Author Share Posted October 20, 2008 but then it adds too many for the ones with more than one set of parenthesis. Quote Link to comment Share on other sites More sharing options...
rhodesa Posted October 20, 2008 Share Posted October 20, 2008 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>'; ?> Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted October 20, 2008 Author Share Posted October 20, 2008 Cool, seems to be working! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.