3 Commits

Author SHA1 Message Date
43bf260887 Implement 2023 day 10 part 2 2023-12-10 11:45:18 +01:00
f1b23b0116 Implement 2023 day 10 part 1 2023-12-10 10:38:16 +01:00
126eeb7587 Move grid code to common 2023-12-10 09:59:19 +01:00
7 changed files with 234 additions and 51 deletions

View File

@@ -7,6 +7,7 @@ use std::ops::Index;
use std::ops::IndexMut;
use std::ops::Sub;
use anyhow::Context;
use anyhow::Result;
use nom::combinator::map;
use nom::error::ErrorKind;
@@ -53,6 +54,7 @@ pub fn parse_input<'a, O>(
///
/// This implementation is based on [`nom::multi::fold_many1`] with minor differences. If
/// successful, this should probably be upstreamed.
#[allow(unused)]
pub fn reduce_many1<I, O, E, F>(
mut f: F,
mut g: impl FnMut(O, O) -> O,
@@ -104,6 +106,7 @@ where
}
/// Add an index to repeated successful invocations of the embedded parser.
#[allow(unused)]
pub fn enumerate<I, O, E>(f: impl Parser<I, O, E>) -> impl FnMut(I) -> IResult<I, (usize, O), E> {
let mut index = 0usize;
@@ -115,6 +118,7 @@ pub fn enumerate<I, O, E>(f: impl Parser<I, O, E>) -> impl FnMut(I) -> IResult<I
}
/// Return the minimum and maximum of two unordered variables
#[allow(unused)]
pub fn minmax<T>(a: T, b: T) -> (T, T)
where
T: PartialOrd,
@@ -127,6 +131,7 @@ where
}
/// Some magic to get two mutable references into the same slice
#[allow(unused)]
pub fn get_both<T>(slice: &mut [T], first: usize, second: usize) -> (&mut T, &mut T) {
match first.cmp(&second) {
Ordering::Greater => {
@@ -186,9 +191,11 @@ impl IndexSet {
}
}
#[allow(unused)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Vec2(pub [i32; 2]);
#[allow(unused)]
impl Vec2 {
pub fn l1(self) -> i32 {
self.0.into_iter().map(i32::abs).sum()
@@ -234,3 +241,54 @@ impl IndexMut<usize> for Vec2 {
&mut self.0[index]
}
}
pub struct Grid<'a> {
width: usize,
data: &'a [u8],
}
impl<'a> Grid<'a> {
pub fn new(data: &'a [u8]) -> anyhow::Result<Self> {
let width = 1 + data
.iter()
.position(|&c| c == b'\n')
.context("Failed to find end of line in grid")?;
anyhow::ensure!(
data.len() % width == 0,
"Grid should divide equally into rows"
);
Ok(Self { width, data })
}
pub fn height(&self) -> usize {
self.data.len() / self.width
}
pub fn width(&self) -> usize {
self.width - 1
}
pub fn rows(&self) -> impl Iterator<Item = &'a [u8]> {
let width = self.width();
self.data
.chunks_exact(self.width)
.map(move |row| &row[..width])
}
pub fn find(&self, c: u8) -> Option<(usize, usize)> {
let pos = self.data.iter().position(|&d| d == c)?;
Some((pos % self.width, pos / self.width))
}
}
impl<'a> Index<usize> for Grid<'a> {
type Output = [u8];
fn index(&self, y: usize) -> &Self::Output {
let offset = y * self.width;
&self.data[offset..(offset + self.width())]
}
}

View File

@@ -1,52 +1,6 @@
use std::collections::HashMap;
use std::ops::Index;
use anyhow::Context;
struct Grid<'a> {
width: usize,
data: &'a [u8],
}
impl<'a> Grid<'a> {
pub fn new(data: &'a [u8]) -> anyhow::Result<Self> {
let width = 1 + data
.iter()
.position(|&c| c == b'\n')
.context("Failed to find end of line in grid")?;
anyhow::ensure!(
data.len() % width == 0,
"Grid should divide equally into rows"
);
Ok(Self { width, data })
}
pub fn height(&self) -> usize {
self.data.len() / self.width
}
pub fn width(&self) -> usize {
self.width - 1
}
pub fn rows(&self) -> impl Iterator<Item = &'a [u8]> {
let width = self.width();
self.data
.chunks_exact(self.width)
.map(move |row| &row[..width])
}
}
impl<'a> Index<usize> for Grid<'a> {
type Output = [u8];
fn index(&self, y: usize) -> &Self::Output {
let offset = y * self.width;
&self.data[offset..(offset + self.width())]
}
}
use crate::common::Grid;
fn is_surrounded(grid: &Grid<'_>, y: usize, start: usize, last: usize) -> bool {
fn is_symbol(c: u8) -> bool {

View File

@@ -1,7 +1,144 @@
pub fn part1(_input: &[u8]) -> anyhow::Result<String> {
anyhow::bail!("Not implemented")
use std::collections::VecDeque;
use anyhow::Context;
use crate::common::Grid;
use crate::common::IndexSet;
const LEFT: u8 = 1;
const RIGHT: u8 = 2;
const UP: u8 = 4;
const DOWN: u8 = 8;
fn get_connections(c: u8) -> u8 {
match c {
b'|' => UP | DOWN,
b'-' => LEFT | RIGHT,
b'F' => DOWN | RIGHT,
b'J' => LEFT | UP,
b'L' => RIGHT | UP,
b'7' => LEFT | DOWN,
_ => 0,
}
}
pub fn part2(_input: &[u8]) -> anyhow::Result<String> {
anyhow::bail!("Not implemented")
fn find_cycle(map: &Grid<'_>) -> anyhow::Result<(usize, bool, IndexSet)> {
let (start_x, start_y) = map.find(b'S').context("Couldn't find starting point")?;
let mut visited = IndexSet::with_capacity(map.width() * map.height());
let mut todo = VecDeque::new();
visited.insert(start_y * map.width() + start_x);
let mut start_up = false;
if start_x > 0 && (get_connections(map[start_y][start_x - 1]) & RIGHT) != 0 {
todo.push_back((1, (start_x - 1, start_y)));
visited.insert(start_y * map.width() + start_x - 1);
}
if start_x + 1 < map.width() && (get_connections(map[start_y][start_x + 1]) & LEFT) != 0 {
todo.push_back((1, (start_x + 1, start_y)));
visited.insert(start_y * map.width() + start_x + 1);
}
if start_y > 0 && (get_connections(map[start_y - 1][start_x]) & DOWN) != 0 {
todo.push_back((1, (start_x, start_y - 1)));
visited.insert((start_y - 1) * map.width() + start_x);
start_up = true;
}
if start_y + 1 < map.height() && (get_connections(map[start_y + 1][start_x]) & DOWN) != 0 {
todo.push_back((1, (start_x, start_y + 1)));
visited.insert((start_y + 1) * map.width() + start_x);
}
let mut max_dist = 1;
while let Some((dist, (x, y))) = todo.pop_front() {
let mut enqueue = |x, y| {
if visited.insert(y * map.width() + x) {
todo.push_back((dist + 1, (x, y)));
// Can elide comparison because we do a BFS and length is strictly increasing
max_dist = dist + 1;
}
};
let connections = get_connections(map[y][x]);
if (connections & LEFT) != 0 {
enqueue(x - 1, y);
}
if (connections & RIGHT) != 0 {
enqueue(x + 1, y);
}
if (connections & UP) != 0 {
enqueue(x, y - 1);
}
if (connections & DOWN) != 0 {
enqueue(x, y + 1);
}
}
Ok((max_dist, start_up, visited))
}
pub fn part1(input: &[u8]) -> anyhow::Result<String> {
let map = Grid::new(input)?;
find_cycle(&map).map(|(max_dist, _, _)| max_dist.to_string())
}
pub fn part2(input: &[u8]) -> anyhow::Result<String> {
let map = Grid::new(input)?;
let (_, s_up, visited) = find_cycle(&map)?;
let mut inside = 0;
for (y, row) in map.rows().enumerate() {
let y_offset = y * map.width();
let mut pipes = 0;
for (x, &c) in row.iter().enumerate() {
if visited.contains(y_offset + x) {
let is_up = match c {
b'|' | b'J' | b'L' => true,
b'S' => s_up,
_ => false,
};
if is_up {
pipes += 1;
}
} else {
inside += pipes % 2;
}
}
}
Ok(inside.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE: &[u8] = include_bytes!("samples/10.1.txt");
const SAMPLE2: &[u8] = include_bytes!("samples/10.2.txt");
const SAMPLE3: &[u8] = include_bytes!("samples/10.3.txt");
const SAMPLE4: &[u8] = include_bytes!("samples/10.4.txt");
#[test]
fn sample_part1() {
assert_eq!("8", part1(SAMPLE).unwrap());
}
#[test]
fn sample_part2() {
assert_eq!("4", part2(SAMPLE2).unwrap());
assert_eq!("8", part2(SAMPLE3).unwrap());
assert_eq!("10", part2(SAMPLE4).unwrap());
}
}

View File

@@ -0,0 +1,5 @@
..F7.
.FJ|.
SJ.L7
|F--J
LJ...

View File

@@ -0,0 +1,9 @@
...........
.S-------7.
.|F-----7|.
.||.....||.
.||.....||.
.|L-7.F-J|.
.|..|.|..|.
.L--J.L--J.
...........

10
2023/src/samples/10.3.txt Normal file
View File

@@ -0,0 +1,10 @@
.F----7F7F7F7F-7....
.|F--7||||||||FJ....
.||.FJ||||||||L7....
FJL7L7LJLJ||LJ.L-7..
L--J.L7...LJS7F-7L7.
....F-J..F7FJ|L7L7L7
....L7.F7||L7|.L7L7|
.....|FJLJ|FJ|F7|.LJ
....FJL-7.||.||||...
....L---J.LJ.LJLJ...

10
2023/src/samples/10.4.txt Normal file
View File

@@ -0,0 +1,10 @@
FF7FSF7F7F7F7F7F---7
L|LJ||||||||||||F--J
FL-7LJLJ||||||LJL-77
F--JF--7||LJLJ7F7FJ-
L---JF-JLJ.||-FJLJJ7
|F|F-JF---7F7-L7L|7|
|FFJF7L7F-JF7|JL---7
7-L-JL7||F7|L7F-7F7|
L.L7LFJ|||||FJL7||LJ
L7JLJL-JLJLJL--JLJ.L