summaryrefslogtreecommitdiff
path: root/src/day5.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/day5.rs')
-rw-r--r--src/day5.rs65
1 files changed, 65 insertions, 0 deletions
diff --git a/src/day5.rs b/src/day5.rs
new file mode 100644
index 0000000..806ddf2
--- /dev/null
+++ b/src/day5.rs
@@ -0,0 +1,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");
+
+
+} \ No newline at end of file