Find the floor number where Santa ends up on. Starting on the ground floor (floor 0).
(
= go up one floor.
)
= go down one floor.
Simple arithmetics:
const input = '((((()(()'
const up = input.match(/\(/g).length
const down = input.match(/\)/g).length
const result = up - down
console.log(result)
Find the nth parenthesis (starts from 1) which takes Santa to the basement (floor -1).
let floor = 0
const result =
1 +
[...input].findIndex((parenthesis) => {
floor += parenthesis === '(' ? 1 : -1
return floor === -1
})
console.log(result)
Because the first parenthesis is at position 1
(as per the puzzle instructions),
the 1 +
before [...input].findIndex()
is required.
Initializing floor
to 1 and removing the 1 +
would also provide the correct result,
but it would be confusing.
I don't like that I have to use a mutable variable (floor
),
but I can't think of a cleaner solution.
I could use reduce()
,
but I couldn't make it pretty.
Plus it would always loop through the whole input
string;
findIndex()
stops when the result has been found.
Nothing as this was a trivial puzzle.