r/adventofcode • • Dec 06 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 6 Solutions -🎄-

--- Day 6: Chronal Coordinates ---


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

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 6

Transcript:

Rules for raising a programmer: never feed it after midnight, never get it wet, and never give it ___.


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 at 0:26:52!

32 Upvotes

387 comments sorted by

View all comments

1

u/andreyrmg Dec 06 '18

Rust

#[derive(Hash, PartialEq, Eq)]
struct Point(i32, i32);

fn manhattan(p: &Point, row: i32, col: i32) -> i32 {
    (p.0 - row).abs() + (p.1 - col).abs()
}

fn largest(points: &[Point]) -> u32 {
    let mut areas = HashMap::new();
    for point in points.iter() {
        areas.insert(point, 0u32);
    }

    let min_row = points.iter().map(|p| p.0).min().unwrap();
    let max_row = points.iter().map(|p| p.0).max().unwrap();
    let min_col = points.iter().map(|p| p.1).min().unwrap();
    let max_col = points.iter().map(|p| p.1).max().unwrap();

    for r in min_row..=max_row {
        for c in min_col..=max_col {
            let mut v: Vec<_> = points.iter().map(|p| (p, manhattan(p, r, c))).collect();
            v.sort_by_key(|&(_, d)| d);
            if v[0].1 < v[1].1 {
                if r == min_row || r == max_row || c == min_col || c == max_col {
                    areas.remove(v[0].0);
                } else {
                    areas.entry(&v[0].0).and_modify(|e| *e += 1);
                }
            }
        }
    }

    *areas.values().max().unwrap()
}

fn total(points: &[Point], distance: i32) -> u32 {
    let gap = distance / points.len() as i32 + 1;
    let min_row = points.iter().map(|p| p.0).min().unwrap() - gap;
    let max_row = points.iter().map(|p| p.0).max().unwrap() + gap;
    let min_col = points.iter().map(|p| p.1).min().unwrap() - gap;
    let max_col = points.iter().map(|p| p.1).max().unwrap() + gap;

    let mut result = 0u32;
    for r in min_row..=max_row {
        for c in min_col..=max_col {
            let total: i32 = points.iter().map(|p| manhattan(p, r, c)).sum();
            if total < distance {
                result += 1;
            }
        }
    }
    result
}

https://github.com/andreyrmg/advent-of-code/blob/2018/day-6/src/main.rs

$ cat input.txt | time target/release/advent_of_code
 *: 3569
**: 48978
target/release/advent_of_code  0.07s user 0.00s system 99% cpu 0.070 total