Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
33
Task/Balanced-brackets/PHP/balanced-brackets.php
Normal file
33
Task/Balanced-brackets/PHP/balanced-brackets.php
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
#!/usr/bin/php
|
||||
<?php
|
||||
|
||||
# brackets generator
|
||||
function bgenerate ($n) {
|
||||
if ($n==0) return '';
|
||||
$s = str_repeat('[', $n) . str_repeat(']', $n);
|
||||
return str_shuffle($s);
|
||||
}
|
||||
|
||||
function printbool($b) {return ($b) ? 'OK' : 'NOT OK';}
|
||||
|
||||
function isbalanced($s) {
|
||||
$bal = 0;
|
||||
for ($i=0; $i < strlen($s); $i++) {
|
||||
$ch = substr($s, $i, 1);
|
||||
if ($ch == '[') {
|
||||
$bal++;
|
||||
} else {
|
||||
$bal--;
|
||||
}
|
||||
if ($bal < 0) return false;
|
||||
}
|
||||
return ($bal == 0);
|
||||
}
|
||||
|
||||
# test parameters are N (see spec)
|
||||
$tests = array(0, 2,2,2, 3,3,3, 4,4,4,4);
|
||||
|
||||
foreach ($tests as $v) {
|
||||
$s = bgenerate($v);
|
||||
printf("%s\t%s%s", $s, printbool(isbalanced($s)), PHP_EOL);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue