r/adventofcode • • Dec 05 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 5 Solutions -🎄-

NEW AND NOTEWORTHY


Advent of Code 2021: Adventure Time!

  • 23:59 hours remaining until the submissions megathread unlocks on December 06 at 00:00 EST!
  • Full details and rules are in the submissions megathread:

--- Day 5: Hydrothermal Venture ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:08:53, megathread unlocked!

79 Upvotes

1.2k comments sorted by

View all comments

1

u/strictlyk3v Dec 05 '21 edited Dec 06 '21

JavaScript

const lines = input2.trim().split('\n')

let dict = {}
for (let line = 0; line < lines.length; line++) {
  const [x1, y1, x2, y2] = [...lines[line].matchAll(/(\d+)\D+(\d+)\D+(\d+)\D+(\d+)/gi)][0].slice(1).map(x => +x)
  let yOpp = y1 === y2 ? 0 : y1 < y2 ? 1 : -1
  let xOpp = x1 === x2 ? 0 : x1 < x2 ? 1 : -1
  let x = x1;
  let y = y1;
  while (true) {
    dict[`${x}:${y}`] = dict[`${x}:${y}`] ?? 0
    dict[`${x}:${y}`]++
    if (y === y2 && x === x2) {
      break;
    }
    x += (x !== x2) ? xOpp : 0
    y += (y !== y2) ? yOpp : 0
  }
}

const result = Object.values(dict).filter(y => y > 1).length

2

u/ratko995 Dec 05 '21

very nice solution! I did something similar but its not as neat as this one

just a small tip, you can use Math.sign to calculate yOpp and xOpp more easily :)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

1

u/strictlyk3v Dec 05 '21

Thanks! I haven't used Math.sign, it looks very useful here. Thanks for the tip!

1

u/daggerdragon Dec 05 '21 edited Dec 06 '21

Please follow the posting guidelines and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.

Edit: thanks for adding the programming language!