day 5 part 1. Mostly parsing, quite unfun

This commit is contained in:
Nico 2022-12-05 20:57:52 +00:00
parent 6a082267e4
commit 57fd3d6b91
2 changed files with 94 additions and 0 deletions

85
src/bin/05.rs Normal file
View File

@ -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<Instruction> {
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<Vec<char>> {
let mut stacks: Vec<Vec<char>> = Vec::new();
for l in input.lines() {
let lchars: Vec<char> = 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<String> {
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<String> {
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);
}
}

9
src/examples/05.txt Normal file
View File

@ -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