Hey guys, I refactored my super verbose brute force implementation and wanted to talk about my approach a little bit.
You can see my previous post here.
But to recap a little bit, I was to parse a string of numbers and operators, where the operator preceded any numbers, and sum them together.
Like this `- 2 – 6 5`
A pattern emerged here so I decided to use regex to parse that pattern out.
In the Class Method `parse`, I’ve used the following regex pattern: string.scan(/-\s\d\s\d/).
This is saying looking for a ‘-‘ sign, followed by a space, followed by a number(1 or more digits) which is followed by a space and again a number(1 or more digits). Then, create an array where only the strings that match that pattern are included.
This pattern is the important pattern, complex pattern, that is the key to solving the challenge. Everything that is a natural number or whole positive number is just going to be added to the sum, but you must follow the Order of Operations on the negative expressions.
In that sense, I then replace the same pattern with empty strings to build the simple sum string. That leaves me with an array of the patterns that matched for the complex expressions and a string of only the simple expressions and in the end they need to be summed together.
And there you have it. A lot less verbose, and easier to follow by separating the two sums into their own methods.
Until next time!
Leave a Reply