1
0
Fork 0

It works ! \o/

This commit is contained in:
Florent DENEF 2022-12-27 11:11:38 +01:00
parent 066a5894d3
commit 3361c4f973
1 changed files with 40 additions and 18 deletions

View File

@ -1,9 +1,11 @@
use std::collections::VecDeque;
use nom::{
branch::alt,
bytes::complete::{tag, take, take_while1},
combinator::{all_consuming, map, map_res, opt},
sequence::{delimited, preceded, tuple},
Finish, IResult,
Finish,
IResult, sequence::{delimited, preceded, tuple},
};
#[derive(Debug)]
@ -53,16 +55,22 @@ fn parse_crate_line(i: &str) -> IResult<&str, Vec<Option<char>>> {
Ok((i, v))
}
fn transpose_rev<T>(v: Vec<Vec<Option<T>>>) -> Vec<Vec<T>> {
fn transpose_rev<T>(v: Vec<Vec<Option<T>>>) -> Vec<VecDeque<T>> {
assert!(!v.is_empty());
let len = v[0].len();
let len = v
.iter()
.max_by(|x, y| x.len().cmp(&y.len()))
.unwrap_or_else(|| panic!(""))
.len();
println!("{len}, {}", v[0].len());
let mut iters: Vec<_> = v.into_iter().map(|n| n.into_iter()).collect();
(0..len)
.map(|_| {
iters
.iter_mut()
.filter_map(|n| n.next().unwrap())
.collect::<Vec<T>>()
.filter_map(|n| n.next())
.flatten()
.collect::<VecDeque<T>>()
})
.collect()
}
@ -88,7 +96,7 @@ fn parse_instruction(i: &str) -> IResult<&str, Instruction> {
)(i)
}
fn parser(content: &str) {
fn parser(content: &str) -> String {
let mut lines = content.lines();
let crate_lines = (&mut lines)
.map_while(|line| {
@ -99,22 +107,36 @@ fn parser(content: &str) {
})
.collect();
let crate_columns = transpose_rev(crate_lines);
crate_columns.iter().for_each(|item| println!("{item:?}"));
let mut crate_columns = transpose_rev(crate_lines);
assert!(lines.next().unwrap().is_empty());
let instructions: Vec<_> = lines
lines
.map(|line| all_consuming(parse_instruction)(line).finish().unwrap().1)
.collect();
for ins in &instructions {
println!("{ins:?}");
}
.into_iter()
.for_each(|ins| {
(0..ins.quantity).for_each(|_| {
let tmp = crate_columns
.get_mut(ins.src)
.unwrap_or_else(|| {
panic!("Index {} is out of bound of crate_columns.", ins.src)
})
.pop_front()
.unwrap_or_else(|| panic!("Could not pop front the column {}", ins.src));
crate_columns
.get_mut(ins.dst)
.unwrap_or_else(|| panic!("Index {} is out of bound", ins.dst))
.push_front(tmp);
});
});
let mut answer = String::new();
crate_columns
.iter()
.for_each(|item| answer.push(*item.front().unwrap_or_else(|| panic!(""))));
answer
}
pub fn solve(file_path: &str) -> i32 {
pub fn solve(file_path: &str) -> String {
let content = std::fs::read_to_string(file_path).unwrap_or_else(|err| panic!("{err}"));
parser(&content);
0
parser(&content)
}