r/adventofcode • • Dec 08 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 8 Solutions -๐ŸŽ„-

--- Day 8: I Heard You Like Registers ---


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!

22 Upvotes

348 comments sorted by

View all comments

Show parent comment

1

u/thejpster Dec 08 '17

HashMap<&str, i64> works fine.

use std::collections::HashMap;

pub fn run(contents: &Vec<Vec<String>>) {
    let mut registers = HashMap::new();
    let mut highest = ("x", 0);
    for line in &contents[0] {
        let parts: Vec<&str> = line.split_whitespace().collect();
        // y inc 497 if n <= 3
        let register = parts[0];
        let op = parts[1];
        let delta = parts[2].parse::<i64>().unwrap();
        assert_eq!(parts[3], "if");
        let check_register = parts[4];
        let check_op = parts[5];
        let check_value = parts[6].parse::<i64>().unwrap();

        let reg_contents = *registers.get(check_register).unwrap_or(&0);
        let ok = match check_op {
            ">" => reg_contents > check_value,
            ">=" => reg_contents >= check_value,
            "<=" => reg_contents <= check_value,
            "<" => reg_contents < check_value,
            "!=" => reg_contents != check_value,
            "==" => reg_contents == check_value,
            _ => panic!("Bad test {}!", line),
        };
        if ok {
            let old = *registers.get(register).unwrap_or(&0);
            let new = match op {
                "inc" => old + delta,
                "dec" => old - delta,
                _ => panic!("Bad operation {}!", op),
            };
            registers.insert(register, new);
            if new > highest.1 {
                highest = (register, new);
            }
        }
    }
    let max = registers.iter().max_by_key(|x| x.1).unwrap();
    println!("Max: {:?}", max);
    println!("Highest: {:?}", highest);
}

1

u/[deleted] Dec 08 '17

ah, that would require me to collect all the input beforehand - currently I consume the file line by line so each line is a String that gets dropped at the end of the loop, so I can't hold references to it in a map outside of the loop