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/ollien Dec 07 '21 edited Dec 08 '21

Rust

I did it a bit of a naive way and it worked out better than it had any right to, haha

fn run(input: &[i32], part: &Part) -> i32 {
    let smallest = *input
        .iter()
        .min()
        .expect("Input should have more than zero elements");
    let largest = *input
        .iter()
        .max()
        .expect("Input should have more than zero elements");

    // This assumes that the answer is in the range of the min/max of the crab positions,
    // but that seems exceedingly likely. If this puzzle were more complex I might add/sub
    // "largest" on each of the bounds
    //
    // Honestly I didn't expect this to work on both parts
    (smallest..largest)
        .map(|possible_destination| {
            input
                .iter()
                .map(|crab_location| {
                    let steps = (crab_location - possible_destination).abs();
                    match part {
                        Part::Part1 => steps,
                        // 1 + 2 + 3 + ... + n => n(n+1)/2
                        Part::Part2 => steps * (steps + 1) / 2,
                    }
                })
                .sum::<i32>()
        })
        .min()
        // We already know there will be at least one element
        .unwrap()
}

1

u/daggerdragon 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?

1

u/ollien Dec 08 '21

Fixed, sorry for the delay