summaryrefslogtreecommitdiff
path: root/src/day5.rs
blob: efc0cc334e3adc11043e36e351c3765b18ebd5a7 (plain)
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
use std::{collections::HashMap};
use regex::Regex;

pub fn run(input: String) {
    let lines: Vec<&str> = input.lines().collect();
    let mut lix: usize = 0;
    let mut ship: HashMap<usize, Vec<char>> = HashMap::new();
    for line in lines.iter() {
        lix += 1;
        let chrs: Vec<char> = line.chars().collect();
        // Line with just container numbers after the containers themselves
        if chrs[1] == '1' {
            break;
        }
        for (ix, container) in chrs.chunks(4).enumerate() {
            let stack = ship.entry(ix+1).or_insert(Vec::new());// key starts at 1, of course
            let payload = container[1];
            if payload.is_alphabetic() {
                stack.insert(0, payload) // last one we found is always the bottom of the stack
            }
        }
    }
    //println!("ship: {:?}", ship);
    lix += 1;


    let re = Regex::new(r"^move (\d+) from (\d+) to (\d+)$").unwrap();
    assert!(re.is_match("move 1 from 2 to 4"));
    for line in lines[lix..].iter() {
        // parse the instruction... 
        // "move 1 from 2 to 1"

        let mm = re.captures(line).expect("instruction didn't match regex???");
        let n: usize = mm.get(1).unwrap().as_str().parse().unwrap();
        let ifrom: usize = mm.get(2).unwrap().as_str().parse().unwrap();
        let ito: usize = mm.get(3).unwrap().as_str().parse().unwrap();
        //println!("moving {} from {} to {}", n, ifrom, ito);
        // for _ in 0..n {
        //     let stackfrom = ship.get_mut(&ifrom).expect("couldn't find stack to pop from!");
        //     let ch = stackfrom.pop().expect("failed to pop from stack! maybe it was empty?");
        //     let stackto = ship.get_mut(&ito).expect("couldn't find stack to push to!");
        //     stackto.push(ch);
        // }
        let stackfrom = ship.get_mut(&ifrom).expect("couldn't find stack to pop from!");
        let mut chunk: Vec<char> = Vec::new();
        for _ in 0..n {
            let ch = stackfrom.pop().expect("failed to pop from stack! maybe it was empty?");
            chunk.push(ch);
        }
        let stackto = ship.get_mut(&ito).expect("couldn't find stack to push to!");
        for _ in 0..n {
            let ch = chunk.pop().unwrap();
            stackto.push(ch);
        }
    }

    print!("day 5: ");
    for i in 1..(ship.keys().len()+1) {
        let topch = ship.get(&i).unwrap().last().unwrap();
        print!("{}", topch);
    }
    print!("\n");
    

}