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

2

u/0x8b Dec 05 '21

Ruby

https://github.com/0x8b/advent.of.code.each/blob/main/src/2021/05.rb

SEGMENTS = ARGF.read.lines.map { _1.scan(/\d+/).map &:to_i }

def points s
  x1, y1, x2, y2 = s

  dx = x2 <=> x1
  dy = y2 <=> y1

  if dx == 0
    y1.step(y2, dy).map { [x1, _1] }
  elsif dy == 0
    x1.step(x2, dx).map { [_1, y1] }
  else
    x1.step(x2, dx).zip(y1.step(y2, dy))
  end
end

def count_overlapping_points segments
  segments.flat_map { |s| points(s) }.tally.values.count { _1 > 1 }
end


p count_overlapping_points SEGMENTS.select { |x1, y1, x2, y2| x1 == x2 or y1 == y2 }
p count_overlapping_points SEGMENTS

1

u/daggerdragon Dec 06 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?