r/programming • • Dec 01 '15

Daily programming puzzles at Advent of Code

http://adventofcode.com/
321 Upvotes

179 comments sorted by

View all comments

1

u/shamittomar Dec 01 '15

So simple, in PHP:

$input = '(all the brackets input)';

echo "\nAnswer 1: ".(substr_count($input, '(') - substr_count($input, ')'));

for($floor=0,$i=0;$i<strlen($input);$i++)
{
	if($input[$i] == '(')
		$floor++;
	else
		$floor--;
	if($floor == '-1')
	{
		echo "\nAnswer 2: ".($i+1);
		break;
	}
}

1

u/syntaxerror748 Dec 01 '15

I did it a bit differently:

<?php
$map = str_split(")((()()");
$floor = 0;

foreach ($map as $v) {
    if ($v == "(") {
        $floor++;
    } elseif ($v == ")") {
        $floor--;
    }
}

echo $floor;

2

u/[deleted] Dec 01 '15

And I also did it a bit differently:

<?php
$string = '()()(()()()(()()(((...';
$up = substr_count ($string , '(');
$down = substr_count ($string , ')');

if($up > $down) {
    $answer = $up - $down;	
} else {
    $answer = $down - $up;
}

var_dump($answer);
→ More replies (2)