advent_of_code_2022/aoc_05a/src/main.rs

77 lines
2.1 KiB
Rust

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn prep_array(result: &mut Vec<Vec<char>>, line: String) {
for (i, c) in line.chars().enumerate() {
if i % 4 == 1 && c.is_alphabetic() {
while 1 + i / 4 > result.len() {
result.push(Vec::<char>::new());
}
result[i / 4].insert(0 , c);
}
}
}
fn move_array(result: &mut Vec<Vec<char>>, line: String) {
let mut cnt: usize = 0;
let mut src: usize = 0;
for (i, token) in line.split(" ").enumerate() {
match i {
1 => cnt = token.parse().unwrap(),
3 => src = token.parse().unwrap(),
5 => {
src -= 1;
let mut dst: usize = token.parse().unwrap();
dst -= 1;
let mut j = result[src].len() - 1;
for _k in 0..cnt {
let mem = result[src][j];
result[src].pop();
result[dst].push(mem);
if j > 0 {
j -= 1;
}
}
},
_ => (),
}
}
}
fn main() {
let file_path = String::from("input");
let mut result = Vec::<Vec<char>>::new();
println!("In file {}", file_path);
if let Ok(lines) = read_lines(file_path) {
// Consumes the iterator, returns an (Optional) String
for line in lines {
if let Ok(ip) = line {
if ip.len() > 0 {
match &ip[..1] {
"[" => prep_array(&mut result, ip),
" " => prep_array(&mut result, ip),
"m" => move_array(&mut result, ip),
_ => ()
}
}
}
}
}
let mut res = String::from("");
for i in 0..result.len() {
res.push(result[i][result[i].len() - 1]);
}
println!("{}", res);
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}