DEV Community

Cover image for Advent of code - Day 18
Quentin Ménoret
Quentin Ménoret

Posted on

Advent of code - Day 18

Are you participating in the Advent of code this year?

If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!

I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.

This one was super fun! I't just a question of priorities and RegEx, but it took me a while to have it working properly.

Not going to lie, I took the easy way and used eval to calculate the expression as soon as I had them in the right order!

Here is my solution for day #18:

function run(str) {
  // + operations
  if (str.match(/\d+ \+ \d+/)) {
    const substr = /\d+ \+ \d+/.exec(str)[0]
    return run(str.replace(substr, eval(substr)))
  }
  // if there is a number alone in a parenthesis, remove the parenthesis
  if (str.match(/\(\d+\)/)) {
    const aloneNumber = /\(\d+\)/.exec(str)[0]
    return run(str.replace(aloneNumber, aloneNumber.slice(1, -1)))
  }
  // otherwise extract the content of a parenthesis
  if (str.match(/\(\d+( [\*,\+] \d+)+\)/)) {
    const parenthesisContent = /\(\d+( [\*,\+] \d+)+\)/.exec(str)[0]
    return run(str.replace(parenthesisContent, run(parenthesisContent.slice(1, -1))))
  }
  return eval(str)
}

console.log(input.reduce((acc, str) => acc + run(str), 0))
Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!


Photo by Markus Spiske on Unsplash

Top comments (0)