[Coding] Solving Problems (Advent of Code 2015 Day 1)

Posted by Khatharsis on November 14, 2016

I finished a LINQ course on Pluralsight and the author mentioned Advent of Code. Curious, I went to check it out and found it is similar to Project Euler — short programming problems to solve in an open-ended way such that if you want to practice a new language, problem solving skills, etc., it’s a good platform for that. I’ve only looked at 2015’s Day 1 problem so far, but while thinking about my initial solution, I came up with a second solution, then wondered if it could be improved on. Eventually I ended up back at my first solution.

I found it an interesting process that I decided it was worth writing about.

The basic premise of the problem is you are given a string containing open parenthesis (parens), “(“, and close parens, “)”. An open paren = 1, a close paren = -1. Your task is to find the final value after parsing the entire string. Initial start value is 0.

The algorithm to solve it is pretty simple, assuming we don’t have to do any error checking:


var value = 0;
for (var i = 0; i < str.length; i++) {
    value = (str[i] == "(") ? (value + 1) : (value - 1)
}
return value;

(JavaScript is my "scratchpad" language.)

My next thought was, I can make it "easier" by counting all of the open parens and close parens, then find the difference to get my final value. Indeed, a quick google search of solutions showed that this was a popular solution. However, if you are using LINQ or a built-in string method to do the count for you, you'd be looping through twice, once to find the count of open parens and again to find the count of close parens.

You can construct your own loop to count the open and close parens, store them in separate variables, and then find the difference. Or since you're looping through it already, just do the math inside and save yourself a variable. Which led back to my original solution.

Less is better, unless it starts to make code hard to read. I feel this is a simple enough problem and solution for intermediate learners that it's not necessary to bring in the second variable. Though, an if-else statement instead of a tertiary statement may help clarify the syntax for programming learners.