diff options
Diffstat (limited to '05/src/part-2.rs')
-rw-r--r-- | 05/src/part-2.rs | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/05/src/part-2.rs b/05/src/part-2.rs new file mode 100644 index 0000000..9979f6f --- /dev/null +++ b/05/src/part-2.rs @@ -0,0 +1,88 @@ +mod stack; +use stack::{Stack}; + +use std::io::{BufRead}; + +enum State { + Initial, + Skip, + Instructions +} + +fn main() { + let stdin = std::io::stdin(); + let mut handle = stdin.lock(); + + let mut stacks: Vec<Stack<u8>> = Vec::new(); + let mut intermediate_stack: Stack<u8> = Stack::new(); + let mut state: State = State::Initial; + let mut initial_configuration: Vec<Vec<u8>> = Vec::new(); + let mut buf: Vec<u8> = Vec::new(); + + loop { + buf.clear(); + let num_bytes = handle.read_until(b'\n', &mut buf).expect("IO error"); + if num_bytes == 0 { break; } + + match state { + State::Initial => { + if buf.contains(& b'[') { + initial_configuration.push(buf.clone()); + } + else { + state = State::Skip; + } + }, + State::Skip => { + stacks = std::iter::repeat(Stack::new()).take(initial_configuration[0].len()/4).collect(); + for line in (&initial_configuration).into_iter().rev() { + for i in 0..stacks.len() { + let x: u8 = line[4*i + 1]; + if x != b' ' { + stacks[i].push(x); + } + } + //println!("CFG: {}", line[5]); + } + state = State::Instructions; + }, + State::Instructions => { + buf.pop(); // Drop newline. + let mut words = buf.split(|c| c == &b' '); + let w0 = words.next().expect("Malformed input"); + let w1 = words.next().expect("Malformed input"); + let w2 = words.next().expect("Malformed input"); + let w3 = words.next().expect("Malformed input"); + let w4 = words.next().expect("Malformed input"); + let w5 = &words.next().expect("Malformed input"); + assert_eq!(w0, b"move"); + assert_eq!(w2, b"from"); + assert_eq!(w4, b"to"); + + let count: usize = std::str::from_utf8(w1).expect("Malformed input") + .parse().expect("Malformed input"); + let from: usize = std::str::from_utf8(w3).expect("Malformed input") + .parse().expect("Malformed input"); + let to: usize = std::str::from_utf8(w5).expect("Malformed input") + .parse().expect("Malformed input"); + + intermediate_stack.clear(); + + for _ in 0..count { + let x = stacks[from-1].pop().unwrap(); + intermediate_stack.push(x); + } + for _ in 0..count { + stacks[to-1].push(intermediate_stack.pop().unwrap()); + } + } + } + } + + + for stack in stacks { + let x: char = char::from(*stack.peek().unwrap()); + print!("{}", x); + } + println!(""); +} |