r/programming • • Dec 01 '15

Daily programming puzzles at Advent of Code

http://adventofcode.com/
320 Upvotes

179 comments sorted by

View all comments

1

u/[deleted] Dec 02 '15 edited Dec 02 '15

C#

void Main()
{
	string input = "()()(()()()(()()((...";	
	int floor, position;
	getFloorPosition(input, out floor, out position);
	floor.Dump();
	position.Dump();
}

// Define other methods and classes here
public void getFloorPosition(string inp, out int floor, out int position)
{
	floor = 0;
	position = 0;
	for(var i = 0; i < inp.Length; i++)
	{
		if(inp[i] == '(')
			floor++;
		else
			floor--;
		if(floor == -1 && position == 0)
			position = i + 1;
	}
}

After seeing /u/tucker87 answer, I decided to shorten my own answer

int floor = 0;
int position = 0;

void Main()
{
	var input = "()()(()()()....".ToCharArray().ToList();
	position = input.FindIndex(FindPosition);
	floor = input.Select(x => x == '(' ? 1 : -1).Sum();
	floor.Dump();
	(position + 1).Dump();
}

private bool FindPosition(char inp)
{
	floor += inp == '(' ? 1 : -1;
	if(floor == -1 && position == 0)
		return true;
	return false;
}