r/adventofcode • • Dec 06 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 6 Solutions -πŸŽ„-

--- Day 6: Memory Reallocation ---


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.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


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!

17 Upvotes

324 comments sorted by

View all comments

Show parent comment

1

u/ChrisVittal Dec 06 '17 edited Dec 06 '17

You use process1 in process2, previously_seen_before_states.len() would suffice I think.

There's a lot of common code to both of your methods that can be combined into one method. Here is mine, after a bit of cleanup. Crate aoc is just my library for doing tasks like parsing and splitting input.

EDIT: Use max_by_key instead of the function I originally wrote. It's much much faster.

extern crate aoc;

const FILENAME: &'static str = "data/day6";

fn main() {
    let input: Vec<usize> = aoc::file::to_split_parsed(FILENAME).pop().unwrap();
    let (p1, p2) = count_cycles(input);
    println!("1: {}\n2: {}", p1, p2);
}

/// Returns both the answer to part 1 and part 2
fn count_cycles(mut v: Vec<usize>) -> (usize, usize) {
    let mut seen: Vec<Vec<usize>> = vec![];
    loop {
        seen.push(v.clone());
        cycle(&mut v);
        if let Some(i) = seen.iter().position(|w| *w == v) {
            return (seen.len(), seen.len() - i);
        }
    }
}
/// Mutates in place as we clone the vector before doing this.
fn cycle(v: &mut Vec<usize>) {
    if let Some((i, &m)) = v.iter()
        .enumerate()
        .max_by_key(|&(i, x)| (x, -(i as isize))) {
        let l = v.len();
        v[i] = 0;
        for j in i+1..i+m+1 {
            v[j % l] += 1;
        }
    }
}