8

Advent of code - Day 18

 3 years ago
source link: https://dev.to/qmenoret/advent-of-code-day-18-4a5d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Advent of code (17 Part Series)

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 modeExit fullscreen mode

Feel free to share your solution in the comments!


Photo by Markus Spiske on Unsplash


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK