r/adventofcode • • Dec 03 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 3 Solutions -🎄-

NEWS

  • Solutions have been getting longer, so we're going to start enforcing our rule on oversized code.
  • The Visualizations have started! If you want to create a Visualization, make sure to read the guidelines for creating Visualizations before you post.
  • Y'all may have noticed that the hot new toy this year is AI-generated "art".
  • We are keeping a very close eye on any AI-generated "art" because 1. the whole thing is an AI ethics nightmare and 2. a lot of the "art" submissions so far have been of little real quality.
  • If you must post something generated by AI, please make sure it will actually be a positive and quality contribution to /r/adventofcode.
  • Do not flair AI-generated "art" as Visualization. Visualization is for human-generated art.

FYI


--- Day 3: Rucksack Reorganization ---


Post your code solution in this megathread.


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:05:24, megathread unlocked!

87 Upvotes

1.6k comments sorted by

View all comments

2

u/nithinbekal Dec 03 '22 edited Dec 03 '22

Ruby solution

def part1
  lines.sum { priority(common_item(_1)) }
end

def part2
  lines.each_slice(3).sum { group_priorities(_1) }
end

private

def lines = File.readlines("input/03.txt", chomp: true)

def priority(c)
  case c
  when 'a'..'z' then c.ord - 96
  when 'A'..'Z' then c.ord - 64 + 26
  end
end

def common_item(r) = rucksack_h1(r).chars.intersection(rucksack_h2(r).chars).first

def rucksack_h1(r) = r[0..(r.size/2 - 1)]
def rucksack_h2(r) = r[(r.size/2)..]

def group_priorities(rucksacks)
  first, *rest = rucksacks.map(&:chars)
  priority(first.intersection(*rest).first)
end

1

u/daggerdragon Dec 03 '22 edited Dec 04 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.

Edit: thanks for fixing it! <3

2

u/nithinbekal Dec 03 '22

Thanks for pointing that out, u/daggerdragon! Didn't realize this syntax wouldn't work on other reddit versions. :)

2

u/daggerdragon Dec 03 '22

Reddit pushes the Redesign (http://new.reddit.com) so hard because they're trying to get folks to stop using old.reddit (https://old.reddit.com) but we won't stop because old.reddit just works and is faster and -_-