r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


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

edit: Leaderboard capped, thread unlocked!

47 Upvotes

407 comments sorted by

View all comments

Show parent comment

1

u/charismotron Dec 02 '18

TIL: Array#count exists

TIL: Array#count takes a block.

I thought about zip but couldn't think of a way to make it work - forgetting there'd be nested arrays.

4

u/_liquidlemon Dec 02 '18

I managed to do it using zip, you might like it

ids = DATA.readlines.map(&:chomp)
two = 0
three = 0
ids.each do |id|
  counts = id.chars.group_by(&:itself).values.map(&:length).uniq
  two += 1 if counts.include? 2
  three += 1 if counts.include? 3
end
checksum = two * three
puts "Part 1: #{checksum}"

ids.product(ids) do |x, y|
  same = x.chars.zip(y.chars).select { |a, b| a == b }.map(&:first)
  if same.length == x.length - 1
    puts "Part 2: #{same.join}"
    break
  end
end

2

u/Unihedron Dec 02 '18

It's actually also on Enumerable, so you can directly .count lines on STDIN, except unfortunately we need to use it twice in this case!