Advent of code - Day 18

qmenoret

Quentin Ménoret

Posted on December 19, 2020

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

💖 💪 🙅 🚩
qmenoret
Quentin Ménoret

Posted on December 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of code - Day 23
javascript Advent of code - Day 23

December 24, 2020

Advent of code - Day 22
javascript Advent of code - Day 22

December 23, 2020

Advent of code - Day 21
javascript Advent of code - Day 21

December 22, 2020

Advent of code - Day 18
javascript Advent of code - Day 18

December 19, 2020

Advent of code - Day 17
javascript Advent of code - Day 17

December 18, 2020