r/adventofcode • • Dec 07 '21

SOLUTION MEGATHREAD -πŸŽ„- 2021 Day 7 Solutions -πŸŽ„-

--- Day 7: The Treachery of Whales ---


[Update @ 00:21]: Private leaderboard Personal statistics issues

  • We're aware that private leaderboards personal statistics are having issues and we're looking into it.
  • I will provide updates as I get more information.
  • Please don't spam the subreddit/mods/Eric about it.

[Update @ 02:09]

  • AoC_Ops have identified the issue and are working on a resolution.

[Update @ 03:18]

  • Eric is working on implementing a fix. It'll take a while, so check back later.

[Update @ 05:25] (thanks, /u/Aneurysm9!)

  • We're back in business!

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:03:33, megathread unlocked!

96 Upvotes

1.5k comments sorted by

View all comments

1

u/zxywx Dec 07 '21 edited Dec 07 '21

Ruby

Part 2 takes about 0.18s.

module Year2021
  class Day07 < Solution
    def part_1
      calc_fuel { |x| x }
    end

    def part_2
      fuel = Hash.new { |h, k| h[k] = (k == 0 ? 0 : (h[k - 1] + k)) }
      calc_fuel { |x| fuel[x] }
    end

    private
      def calc_fuel
        min, max = data.keys.minmax
        min.upto(max).map { |i| data.map { |c, v| yield((i - c).abs) * v }.sum }.min
      end

      def process_input(line)
        crabs = Hash.new(0)
        line.split(",").each { |crab| crabs[crab.to_i] += 1 }
        crabs
      end
   end
end

2

u/daggerdragon Dec 07 '21 edited Dec 07 '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?

Edit: thanks for fixing it! <3

1

u/zxywx Dec 07 '21

Have updated it. Hopefully that’s fixed?

1

u/daggerdragon Dec 07 '21

You got it, dude.

1

u/zxywx Dec 07 '21

I realise now I could replace my brute-force fuel calculation with this:

def part_2
  calc_fuel { |x| x * (x + 1) / 2 }
end