1
0
This commit is contained in:
2022-12-23 20:52:52 +00:00
parent c67298eb5a
commit 87f14bbf0c
4 changed files with 603 additions and 0 deletions

75
day5/src/main.rs Normal file
View File

@ -0,0 +1,75 @@
fn print_stacks(stacks: &Vec<Vec<char>>) {
for stack in stacks {
println!("{:?}", stack);
}
}
fn stacks_message(stacks: &Vec<Vec<char>>) -> String {
stacks.iter().map(|v| {
v[v.len() - 1]
}).fold(String::new(), |mut s, c| {
s.push(c);
s
})
}
fn main() {
const INPUT: &str = include_str!("../input.txt");
let chunks = INPUT.split_once("\n\n").unwrap();
let mut stack_lines: Vec<String> = chunks.0.lines().map(|x| -> String {
x.to_string() + " "
}).collect();
stack_lines.pop();
let num_stacks = (stack_lines[0].len() + 1) / 4;
let mut stacks: Vec<Vec<char>> = vec![Vec::<char>::new(); num_stacks];
for line in stack_lines.iter().rev() {
let mut line = line.to_string();
line += " ";
for i in 0..num_stacks {
let c = line.chars().nth(i*4 + 1).unwrap();
if c.is_whitespace() {
continue;
}
stacks[i].push(c);
}
}
let stacks_copy = stacks.clone();
let move_lines = chunks.1.lines();
for line in move_lines {
let split: Vec<&str> = line.split(" ").collect();
let n: usize = split[1].parse().unwrap();
let from = split[3].parse::<usize>().unwrap() - 1;
let to = split[5].parse::<usize>().unwrap() - 1;
for _ in 0..n {
let x = stacks[from].pop().unwrap();
stacks[to].push(x);
}
}
print_stacks(&stacks);
println!("Message: {}\n", stacks_message(&stacks));
let mut stacks = stacks_copy;
let move_lines = chunks.1.lines();
for line in move_lines {
let split: Vec<&str> = line.split(" ").collect();
let n: usize = split[1].parse().unwrap();
let from = split[3].parse::<usize>().unwrap() - 1;
let to = split[5].parse::<usize>().unwrap() - 1;
let len = stacks[from].len();
let mut x: Vec<char> = stacks[from].drain(len-n..len).collect();
stacks[to].append(x.as_mut());
}
print_stacks(&stacks);
println!("Message: {}", stacks_message(&stacks));
}