AoC2022/d05/src/a1.rs
2022-12-11 18:06:33 +01:00

117 lines
2.4 KiB
Rust

struct CargoDock {
stacks : Vec<Vec<char>>,
}
impl CargoDock {
fn new() -> Self {
CargoDock { stacks: vec![] }
}
fn add_stacks(&mut self, s : Vec<Vec<char>>) {
self.stacks = s;
}
fn parse_move(inp : String) -> Vec<i32> {
let mut out_vec = vec![];
inp.split(' ').for_each(|elem| {
match elem.parse::<i32>() {
Ok(r) => {
out_vec.push(r);
}
Err(_) => {}
}
});
out_vec
}
fn execute_move(&mut self, m : String) {
let parsed_move = CargoDock::parse_move(m);
let count = parsed_move[0];
let origin : usize = (parsed_move[1] - 1) as usize;
let destination : usize = (parsed_move[2] - 1) as usize;
for _ in 0..count {
let top = self.stacks[origin].pop().unwrap();
self.stacks[destination].push(top);
}
}
fn get_top_layer(&self) -> String {
let mut s = String::new();
self.stacks.iter().for_each(|vec| {
s.push(*vec.last().unwrap());
});
s
}
}
fn parse_stack(inp : Vec<String>) -> Vec<Vec<char>> {
let mut vec : Vec<Vec<char>> = vec![];
vec.push(vec![]);
inp.iter().for_each(|elem| {
if elem.contains('1') {
return;
}
let res = elem.split(' ').collect::<Vec<&str>>();
let mut space_count = 0;
let mut index = 0;
for s in &res {
if s.is_empty() {
space_count += 1;
} else {
let found_char = s.chars().nth(1).unwrap();
index += space_count / 4;
space_count = 0;
while vec.len() < index + 1 {
vec.push(vec![]);
}
vec[index].push(found_char);
index += 1;
}
}
});
for v in &mut vec {
v.reverse();
}
vec
}
pub fn run(inp :Vec<String>) {
let mut prev = 0;
let mut cd = CargoDock::new();
for i in 0..inp.len() {
if inp[i].is_empty() {
let stacks = parse_stack(inp[0..i].to_vec());
cd.add_stacks(stacks);
prev = i;
break;
}
}
for i in (prev+1)..inp.len() {
cd.execute_move(inp[i].clone());
}
println!("a1: {:?}", cd.get_top_layer());
}