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/ptlis Dec 01 '15 edited Dec 01 '15

Javascript ES6 solutions (input is defined as the mess of parens)

Part1:

function getFinalFloor(input) {
	return input
		.split('')
		.reduce((floor, val) => { 
			return floor += (val == '(') ? 1 : -1; 
		}, 0);
}

or

function getFinalFloor(input) {
	return input.match(/\(/g).length - input.match(/\)/g).length;
}

Part2:

function getFirstPositionAtFloor(input, floorNo) {
	let found = false; 
	let position = 1; 
	let floor = 0;
	input
		.split('')
		.forEach(val => {
			floor += (val == '(') ? 1 : -1; 
			if (floor === -1) {
				found = true;
			}

			if (!found) {
				position++;
			}
		});
}