1
0
Fork 0

Compare commits

...

3 commits

Author SHA1 Message Date
19615ebdb5
Update nom 2025-09-15 21:08:25 +02:00
22ada9b454
Adding edges 2023-10-05 23:29:30 +02:00
47c0f0bf76
Vertices added to graph 2023-10-05 23:08:20 +02:00
4 changed files with 87 additions and 24 deletions

View file

@ -11,8 +11,8 @@ incremental = true
rpath = true
[dependencies]
nom = "7.1.1"
itertools = "0.11.0"
nom = "8.0.0"
itertools = "0.14.0"
camino = "1.1.6"
id_tree = "1.8.0"
color-eyre = "0.6.2"

View file

@ -5,8 +5,8 @@ use nom::{
branch::alt,
bytes::complete::{tag, take, take_while1},
combinator::{all_consuming, map, map_res, opt},
Finish,
IResult, sequence::{delimited, preceded, tuple},
sequence::{delimited, preceded},
Finish, IResult, Parser,
};
#[derive(Debug)]
@ -27,17 +27,17 @@ struct Instruction {
fn parse_crate(i: &str) -> IResult<&str, char> {
let first_char = |s: &str| s.chars().next().unwrap();
let f = delimited(tag("["), take(1_usize), tag("]"));
map(f, first_char)(i)
map(f, first_char).parse(i)
}
fn parse_hole(i: &str) -> IResult<&str, ()> {
// `drop` takes a value and returns nothing, which is
// perfect for our case
map(tag(" "), drop)(i)
map(tag(" "), drop).parse(i)
}
fn parse_crate_or_hole(i: &str) -> IResult<&str, Option<char>> {
alt((map(parse_crate, Some), map(parse_hole, |_| None)))(i)
alt((map(parse_crate, Some), map(parse_hole, |_| None))).parse(i)
}
fn parse_crate_line(i: &str) -> IResult<&str, Vec<Option<char>>> {
@ -45,7 +45,7 @@ fn parse_crate_line(i: &str) -> IResult<&str, Vec<Option<char>>> {
let mut v = vec![c];
loop {
let (next_i, maybe_c) = opt(preceded(tag(" "), parse_crate_or_hole))(i)?;
let (next_i, maybe_c) = opt(preceded(tag(" "), parse_crate_or_hole)).parse(i)?;
match maybe_c {
Some(c) => v.push(c),
None => break,
@ -79,29 +79,32 @@ fn transpose_rev<T>(v: Vec<Vec<Option<T>>>) -> Vec<VecDeque<T>> {
fn parse_number(i: &str) -> IResult<&str, usize> {
map_res(take_while1(|c: char| c.is_ascii_digit()), |s: &str| {
s.parse::<usize>()
})(i)
})
.parse(i)
}
fn parse_pile_number(i: &str) -> IResult<&str, usize> {
map(parse_number, |i| i - 1)(i)
map(parse_number, |i| i - 1).parse(i)
}
fn parse_instruction(i: &str) -> IResult<&str, Instruction> {
map(
tuple((
(
preceded(tag("move "), parse_number),
preceded(tag(" from "), parse_pile_number),
preceded(tag(" to "), parse_pile_number),
)),
),
|(quantity, src, dst)| Instruction { quantity, src, dst },
)(i)
)
.parse(i)
}
fn parser(content: &str) -> (Vec<VecDeque<char>>, Vec<Instruction>) {
let mut lines = content.lines();
let crate_lines = (&mut lines)
.map_while(|line| {
all_consuming(parse_crate_line)(line)
all_consuming(parse_crate_line)
.parse(line)
.finish()
.ok()
.map(|(_, line)| line)
@ -119,7 +122,13 @@ fn parser(content: &str) -> (Vec<VecDeque<char>>, Vec<Instruction>) {
assert!(lines.next().unwrap().is_empty());
let instructions = lines
.map(|line| all_consuming(parse_instruction)(line).finish().unwrap().1)
.map(|line| {
all_consuming(parse_instruction)
.parse(line)
.finish()
.unwrap()
.1
})
.collect::<Vec<Instruction>>();
(crate_columns, instructions)
}

View file

@ -5,7 +5,7 @@ use nom::{
bytes::complete::{tag, take_while1},
combinator::{all_consuming, map},
sequence::{preceded, separated_pair},
Finish, IResult,
Finish, IResult, Parser,
};
#[derive(Debug)]
@ -58,33 +58,35 @@ fn parse_entry(input: &str) -> IResult<&str, Entry> {
);
let parse_dir = map(preceded(tag("dir "), parse_path), Entry::Dir);
alt((parse_file, parse_dir))(input)
alt((parse_file, parse_dir)).parse(input)
}
fn parse_path(input: &str) -> IResult<&str, Utf8PathBuf> {
map(
take_while1(|c: char| "abcdefghijklmnopqrstuvwxyz./".contains(c)),
Into::into,
)(input)
)
.parse(input)
}
fn parse_ls(input: &str) -> IResult<&str, Ls> {
map(tag("ls"), |_| Ls)(input)
map(tag("ls"), |_| Ls).parse(input)
}
fn parse_cd(input: &str) -> IResult<&str, Cd> {
map(preceded(tag("cd "), parse_path), Cd)(input)
map(preceded(tag("cd "), parse_path), Cd).parse(input)
}
fn parse_command(line: &str) -> IResult<&str, Command> {
let (input, _) = tag("$ ")(line)?;
alt((map(parse_ls, Into::into), map(parse_cd, Into::into)))(input)
alt((map(parse_ls, Into::into), map(parse_cd, Into::into))).parse(input)
}
fn parse_line(input: &str) -> IResult<&str, Line> {
alt((
map(parse_command, Line::Command),
map(parse_entry, Line::Entry),
))(input)
))
.parse(input)
}
fn total_size(tree: &Tree<FsEntry>, node: &Node<FsEntry>) -> color_eyre::Result<u64> {
@ -97,7 +99,7 @@ fn total_size(tree: &Tree<FsEntry>, node: &Node<FsEntry>) -> color_eyre::Result<
fn generate_tree(content: &str) -> color_eyre::Result<Tree<FsEntry>> {
let lines = content.lines().map(|line| {
all_consuming(parse_line)(line)
all_consuming(parse_line).parse(line)
.finish()
.unwrap_or_else(|err| panic!("{err}"))
.1
@ -171,6 +173,7 @@ pub fn solve_part2(content: &str) -> color_eyre::Result<u64> {
.filter(|n| !n.children().is_empty())
.map(|n| total_size(&tree, n).unwrap())
.filter(|&s| s >= minimum_space_to_free)
.min().unwrap();
.min()
.unwrap();
Ok(size_to_remove)
}

View file

@ -0,0 +1,51 @@
use petgraph::matrix_graph::MatrixGraph;
use petgraph::prelude::*;
pub fn solve_part1(content: &str) -> color_eyre::Result<u32> {
let (n_line, numbers) = {
let mut num_rows = 0_usize;
let mut inner_number = Vec::<u32>::new();
content.lines().for_each(|line| {
let mut line_numbers = line
.chars()
.map(|c| c.to_digit(10).unwrap())
.collect::<Vec<u32>>();
inner_number.append(&mut line_numbers);
num_rows += 1;
});
(num_rows, inner_number)
};
let m_element = numbers.len() / n_line;
let _visible_border = (m_element + n_line) * 2 - 4;
let num_slice = numbers.as_slice();
let mut node_indices = vec![NodeIndex::<u16>::default(); num_slice.len()];
let idx_slice = node_indices.as_mut_slice();
let mut graph = MatrixGraph::<u32, u32, Directed>::with_capacity(m_element * n_line);
for j in 0..n_line {
for i in 0..m_element {
let idx = j * m_element + i;
idx_slice[idx] = graph.add_node(num_slice[idx]);
if (i as i64 - 1) >= 0 {
let previous_same_row = idx - 1;
graph.add_edge(idx_slice[idx], idx_slice[previous_same_row], num_slice[idx]);
graph.add_edge(
idx_slice[previous_same_row],
idx_slice[idx],
num_slice[previous_same_row],
);
}
if (j as i64 - 1) >= 0 {
let previous_same_col = idx - m_element;
graph.add_edge(idx_slice[idx], idx_slice[previous_same_col], num_slice[idx]);
graph.add_edge(
idx_slice[previous_same_col],
idx_slice[idx],
num_slice[previous_same_col],
);
}
}
}
Ok(0)
}