r/adventofcode • • Dec 04 '18

SOLUTION MEGATHREAD -πŸŽ„- 2018 Day 4 Solutions -πŸŽ„-

--- Day 4: Repose Record ---


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 4

Transcript:

Today’s puzzle would have been a lot easier if my language supported ___.


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!

38 Upvotes

340 comments sorted by

View all comments

1

u/rjsberry Dec 08 '18

Slipped behind this week, work's been super busy!

RUST

Part 01:

use ::aoc18::day04::*;

const INPUT: &str = include_str!("input/04.txt");

fn main() {
    let sleep_times = batch_sleep_times(INPUT);
    let guard = longest_asleep(&sleep_times);
    let (minute, _) = part01::most_frequent_minute(&sleep_times[&guard]);

    println!("{}", guard * minute);
}

Part 02:

use ::aoc18::day04::*;

const INPUT: &str = include_str!("input/04.txt");

fn main() {
    let sleep_times = batch_sleep_times(INPUT);
    let (guard, minute) = part02::most_frequent_minute(&sleep_times);

    println!("{}", guard * minute);
}

Using the shared module ::aoc18::day04:

use std::{collections::HashMap, iter::once, str::FromStr};

use ::itertools::Itertools;
use ::lazy_static::lazy_static;
use ::regex::Regex;

pub type GuardId = u32;
pub type Minute = u32;

pub mod part01 {
    use super::*;

    /// Finds the most frequent minute asleep for a slice of periods spent asleep.
    /// Returns the minute and the number of times it was encountered in the slice.
    #[inline]
    pub fn most_frequent_minute(minutes: &[(Minute, Minute)]) -> (Minute, usize) {
        minutes
            .iter()
            .fold(HashMap::new(), |mut map, &(min, max)| {
                for minute in min..max {
                    map.entry(minute).and_modify(|m| *m += 1).or_insert(1);
                }
                map
            })
            .into_iter()
            .sorted_by(|a, b| b.1.cmp(&a.1))[0]
    }
}

pub mod part02 {
    use super::*;

    /// Finds the guard who spends a single minute asleep the most from a set of records.
    /// Returns the guard and the most frequent minute spent asleep.
    pub fn most_frequent_minute(
        map: &HashMap<GuardId, Vec<(Minute, Minute)>>,
    ) -> (GuardId, Minute) {
        let result = map
            .iter()
            .map(|(id, times)| (id, part01::most_frequent_minute(&times)))
            .sorted_by(|a, b| (b.1).1.cmp(&(a.1).1))[0];
        (*result.0, (result.1).0)
    }
}

/// Batch a raw set of records into a map of guard ID's and the times that guard spent asleep.
pub fn batch_sleep_times(input: &str) -> HashMap<GuardId, Vec<(Minute, Minute)>> {
    input
        .lines()
        // YYYY-MM-DD HH:MM will sort itself chronologically with no extra work
        .sorted()
        .into_iter()
        // Chunk the sorted input into the following format:
        //
        // ```
        // let batched = &[
        //     vec!["guard_0", "asleep_0", "awake_0", "asleep_1", "awake_1", ... "awake_n"],
        //     vec!["guard_1", "asleep_0", "awake_0", "asleep_1", "awake_1", ... "awake_n"],
        //     ...
        //     vec!["guard_n", "asleep_0", "awake_0", "asleep_1", "awake_1", ... "awake_n"],
        // ];
        // ```
        .batching(|it| {
            if let Some(line) = it.next() {
                if guard_id(line).is_some() {
                    return Some(
                        once(line)
                            .chain(it.take_while_ref(|l| guard_id(l).is_none()))
                            .collect::<Vec<_>>(),
                    );
                }
            }
            None
        })
        // Parse guard ids and minutes from raw records. If the records cannot be parsed they
        // are filtered out, but input guarantees this is never actually the case. The result
        // is predicated on the value from the previous batch containing more than simply a guard
        // ID as this contains no actual useful info.
        .filter_map(|g| extract_sleep_times(&g).filter(|_| g.len() > 1))
        .fold(HashMap::new(), |mut map, (id, sleep_times)| {
            map.entry(id)
                .and_modify(|v| v.extend(&sleep_times))
                .or_insert(sleep_times);
            map
        })
}

#[inline]
fn capture_first_match<F: FromStr>(re: &Regex, text: &str) -> Option<F> {
    re.captures(text)
        .and_then(|captures| captures.get(1).and_then(|c| c.as_str().parse().ok()))
}

#[inline]
fn minute(entry: &str) -> Option<Minute> {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"\[\d{4}-\d{2}-\d{2} \d{2}:(\d{2})\]").unwrap();
    }
    capture_first_match(&RE, entry)
}

#[inline]
fn guard_id(entry: &str) -> Option<GuardId> {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"Guard #(\d+)").unwrap();
    }
    capture_first_match(&RE, entry)
}

#[inline]
pub fn longest_asleep(map: &HashMap<GuardId, Vec<(Minute, Minute)>>) -> GuardId {
    *map.iter()
        .map(|(id, times)| (id, times.iter().fold(0, |acc, pair| acc + pair.1 - pair.0)))
        .sorted_by(|a, b| b.1.cmp(&a.1))[0]
        .0
}

fn extract_sleep_times(entries: &[&str]) -> Option<(GuardId, Vec<(Minute, Minute)>)> {
    if let Some(id) = guard_id(entries[0]) {
        let mut sleep_times = vec![];
        for (start, stop) in entries[1..].iter().tuples() {
            if let (Some(a), Some(b)) = (minute(start), minute(stop)) {
                sleep_times.push((a, b));
            }
        }
        Some((id, sleep_times))
    } else {
        None
    }
}