Yesterday I did the valid parentheses problem and came up with two solutions, that worked. One was overthought while the other was simplicity defined. The next logical question one can ask though is what if we now want to do brace validation? I.e. there are more than just brackets? What if we include curly braces{}, and square brackets?
Example
The first thing that went into my mind is that we’d need to now check which braces we got and compare them to their matching closing bracket. Then how would you do that, maybe store the pairs in an object…
Seriously, that’s how my thought process started. But then I remembered yesterday, took a deep breath, and thought what would be the least amount of code I could add to get it to work. What are we actually trying to achieve?
We want to match all closed brackets.
When you think about it, the logic doesn’t change. We don’t need an object or conditional checks or anything complicated. We just need to change the stopping criteria and the replace regex. That’s all. So I updated yesterday’s code to be;
function validBraces(parens) {
let workString = parens
const re = /(\(\))|(\{\})|(\[\])/g
while(workString.search(re) !== -1) {
workString = workString.replace(re,'')
}
return workString === ''
}
Code language: JavaScript (javascript)
That’s it. That’s all there was to it. Just updating the regex and everything else stayed the same. I also switched from indexOf to search but that’s a trivial quibble.
Could the previous approach also be updated with so little code? No, because we’d need to update the isMatch
to account for the other types of brackets.
I think this makes yesterday’s final solution the better of the two because it is super easy to extend. Software should be soft, i.e. easy to change when new requirements occur. This solution was easy to extend, well easier than the previous one at least.
If you made your own solution to yesterday’s problem, how easy would it be to update it to fit the new requirements? Let me know over on Twitter @phoexer and as always happy coding.
Today I am working on a summation problem made to look like building a tower out of cubic bricks. It’s fun to brute force sometimes.
Coming back to Rust code after a bit of a hiatus with a simple problem… The Two-sum problem. Finding numbers in an array. Yay, fun.
King Pinn: I Salute You. I’m driving halfway across the country and this song is on repeat. Rest in Peace Tonderai Makoni. You were awesome.
After a few weeks off I’m back to business. This is just an update post detailing plans for the rest of the year.
At last we finally have the great reveal, our mystery project was implementing RSA encryption in rust.