diff --git a/src/bin/05.rs b/src/bin/05.rs new file mode 100644 index 0000000..cf50e83 --- /dev/null +++ b/src/bin/05.rs @@ -0,0 +1,85 @@ +use regex::Regex; + +#[derive(Debug)] +pub struct Instruction { + from: usize, + to: usize, + amount: usize +} + +pub fn parse_instructions(input: &str) -> Vec { + let instructionre = Regex::new(r"move (\d+) from (\d+) to (\d+)").unwrap(); + let mut instructions = Vec::new(); + for l in input.lines() { + let matches = instructionre.captures(l).unwrap(); + let amount:usize = matches[1].parse().unwrap(); + let from:usize = matches[2].parse().unwrap(); + let to:usize = matches[3].parse().unwrap(); + instructions.insert(instructions.len(),Instruction{from, to,amount}); + } + instructions +} + +pub fn parse_stacks(input: &str) -> Vec> { + let mut stacks: Vec> = Vec::new(); + for l in input.lines() { + let lchars: Vec = l.chars().collect(); + + if !(l.starts_with(" 1")) { // skip lines with only numbers + for i in 0..(lchars.len()/4)+1 { + if stacks.len() <= i { + stacks.insert(i,Vec::new()); + } + if lchars[(i*4)+1] != ' ' { + stacks[i].insert(0,lchars[(i*4)+1]); + } + } + } + } + stacks + +} + +pub fn part_one(input: &str) -> Option { + let parts: Vec<&str> = input.split("\n\n").collect(); + let mut stacks = parse_stacks(parts[0]); + let instructions = parse_instructions(parts[1]); + for i in instructions { + for _ in 0..(i.amount) { + let x = stacks[i.from-1].pop().unwrap(); + stacks[i.to-1].push(x); + } + } + Some(stacks.iter() + .map(| x | x[x.len()-1].to_string()) // stringify top element of every stack + .reduce(| x, y | x + &y).unwrap()) // and merge into one big string +} + +pub fn part_two(input: &str) -> Option { + let _ = input; + + None +} + +fn main() { + let input = &advent_of_code::read_file("inputs", 5); + advent_of_code::solve!(1, part_one, input); + advent_of_code::solve!(2, part_two, input); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let input = advent_of_code::read_file("examples", 5); + assert_eq!(part_one(&input), Some("CMZ".to_string())); + } + + #[test] + fn test_part_two() { + let input = advent_of_code::read_file("examples", 5); + assert_eq!(part_two(&input), None); + } +} diff --git a/src/examples/05.txt b/src/examples/05.txt new file mode 100644 index 0000000..42ef47f --- /dev/null +++ b/src/examples/05.txt @@ -0,0 +1,9 @@ + [D] +[N] [C] +[Z] [M] [P] + 1 2 3 + +move 1 from 2 to 1 +move 3 from 1 to 3 +move 2 from 2 to 1 +move 1 from 1 to 2