summary refs log tree commit diff homepage
path: root/2017/src/bin/day08.rs
blob: 4266d3109c4e1cc311ce049b94d4bb46a74b3118 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use std::collections::HashMap;
use std::io::{self, Read};

fn solve(input: &str) -> (i32, i32) {
    let mut max = 0;
    let mut regs = HashMap::new();
    for line in input.lines() {
        let mut words = line.split_whitespace();
        let dest = words.next().unwrap();
        let op = words.next().unwrap();
        let val = words.next().unwrap();
        assert_eq!(Some("if"), words.next());
        let src = words.next().unwrap();
        let cmp = words.next().unwrap();
        let rhs = words.next().unwrap();

        let mut val: i32 = val.parse().unwrap();
        if op == "dec" {
            val = -val;
        }
        let rhs: i32 = rhs.parse().unwrap();
        let src = *regs.entry(src.to_owned()).or_insert(0);
        let dest = regs.entry(dest.to_owned()).or_insert(0);

        let cond = match cmp {
            "==" => src == rhs,
            "!=" => src != rhs,
            "<=" => src <= rhs,
            ">=" => src >= rhs,
            "<" => src < rhs,
            ">" => src > rhs,
            _ => unimplemented!(),
        };
        if cond {
            *dest += val;
        }
        if *dest > max {
            max = *dest;
        }
    }
    (regs.values().cloned().max().unwrap(), max)
}

fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();

    println!("Part 1: {}", solve(&input).0);
    println!("Part 2: {}", solve(&input).1);
}

#[test]
fn part1() {
    assert_eq!(1, solve(
"\
b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10
"
    ).0);
}

#[test]
fn part2() {
    assert_eq!(10, solve(
"\
b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10
"
    ).1);
}
c?id=3968224ad89128d743d92c5b121479d6dd67b6c5&follow=1'>Avoid matching ':' in make tagsJune McEnroe 2021-01-19Prefer tag matches not preceded by [[:alnum:]]June McEnroe 2021-01-19Escape \ and / in mtags search patternsJune McEnroe 2021-01-20Use mtags in source-filterJune McEnroe 2021-01-19Add mtags to generate tags for make and mdocJune McEnroe 2021-01-19Map tags to IDs using only [[:alnum:]-._]June McEnroe 2021-01-19Don't use a pager if reading standard inputJune McEnroe 2021-01-19Support BSD make syntax and match *.amJune McEnroe 2021-01-19Match tab following escaped newline in make assignmentsJune McEnroe 2021-01-18Allow matching lexers using first input lineJune McEnroe