Fixed rustfmt warnings
Some checks failed
Continuous integration / Check (push) Successful in 10m8s
Continuous integration / Test Suite (push) Successful in 10m14s
Continuous integration / Rustfmt (push) Successful in 9m54s
Continuous integration / Clippy (push) Failing after 10m10s
Continuous integration / build (push) Successful in 10m14s

This commit is contained in:
Luke Else 2024-10-05 15:06:25 +01:00
parent 966963b6d3
commit 42664687a1
13 changed files with 100 additions and 49 deletions

View File

@ -10,10 +10,7 @@ impl Solution for Day04 {
input: &mut Vec<String>, input: &mut Vec<String>,
) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> { ) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> {
// Remove Card XXX: at start // Remove Card XXX: at start
let cards: Vec<&str> = input let cards: Vec<&str> = input.iter().map(|c| c.split(':').last().unwrap()).collect();
.iter()
.map(|c| c.split(':').last().unwrap())
.collect();
let mut ans = 0; let mut ans = 0;
for card in cards { for card in cards {

View File

@ -74,10 +74,7 @@ impl Day08 {
map.insert( map.insert(
key, key,
( (
l.to_owned() l.to_owned().replace([',', '('], "").trim().to_owned(),
.replace([',', '('], "")
.trim()
.to_owned(),
r.trim().to_owned().replace(')', ""), r.trim().to_owned().replace(')', ""),
), ),
); );

View File

@ -10,7 +10,9 @@ impl Solution for Day16 {
) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> { ) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> {
let grid = input.iter().map(|l| l.as_bytes()).collect::<Vec<_>>(); let grid = input.iter().map(|l| l.as_bytes()).collect::<Vec<_>>();
Ok(Box::new(self.traverse_grid(&grid, (0, 0, Direction::Right)))) Ok(Box::new(
self.traverse_grid(&grid, (0, 0, Direction::Right)),
))
} }
fn part2( fn part2(
@ -22,8 +24,17 @@ impl Solution for Day16 {
// Itterate through every edge piece and record the max energy from a list of all of the combinations // Itterate through every edge piece and record the max energy from a list of all of the combinations
// O(n^2) :( Can't think of a better way of processing this // O(n^2) :( Can't think of a better way of processing this
// r: row, c: col // r: row, c: col
let ans = (0..grid.len()).flat_map(|r| [(r,0,Direction::Right), (r,grid[0].len()-1,Direction::Left)]) let ans = (0..grid.len())
.chain((0..grid[0].len()).flat_map(|c| [(0,c,Direction::Down), (grid.len()-1,c,Direction::Up)])) .flat_map(|r| {
[
(r, 0, Direction::Right),
(r, grid[0].len() - 1, Direction::Left),
]
})
.chain(
(0..grid[0].len())
.flat_map(|c| [(0, c, Direction::Down), (grid.len() - 1, c, Direction::Up)]),
)
.map(|start| self.traverse_grid(&grid, start)) .map(|start| self.traverse_grid(&grid, start))
.max() .max()
.unwrap(); .unwrap();
@ -39,25 +50,35 @@ impl Solution for Day16 {
impl Day16 { impl Day16 {
/// Returns the next coordinate after taking a step in the given direction /// Returns the next coordinate after taking a step in the given direction
fn step(&self, r: usize, c: usize, d: Direction) -> (usize, usize, Direction) { fn step(&self, r: usize, c: usize, d: Direction) -> (usize, usize, Direction) {
let (dr, dc) = [(-1,0),(0,1),(1,0),(0,-1)][d as usize]; let (dr, dc) = [(-1, 0), (0, 1), (1, 0), (0, -1)][d as usize];
((r as isize + dr) as _, (c as isize + dc) as _, d) ((r as isize + dr) as _, (c as isize + dc) as _, d)
} }
/// Function which traverses through the grid and returns the number of tiles that are energised /// Function which traverses through the grid and returns the number of tiles that are energised
/// in the process /// in the process
fn traverse_grid(&self, grid: &[&[u8]], start: (usize,usize, Direction)) -> usize { fn traverse_grid(&self, grid: &[&[u8]], start: (usize, usize, Direction)) -> usize {
let mut energised = vec![vec![[false; 4]; grid[0].len()]; grid.len()]; let mut energised = vec![vec![[false; 4]; grid[0].len()]; grid.len()];
let mut beams = vec![start]; let mut beams = vec![start];
// Direction change given the current direction as an index // Direction change given the current direction as an index
let right_lean = [Direction::Right, Direction::Up, Direction::Left, Direction::Down]; let right_lean = [
let left_lean = [Direction::Left, Direction::Down, Direction::Right, Direction::Up]; Direction::Right,
Direction::Up,
Direction::Left,
Direction::Down,
];
let left_lean = [
Direction::Left,
Direction::Down,
Direction::Right,
Direction::Up,
];
// Trace all of the beams present in the list // Trace all of the beams present in the list
while !beams.is_empty() { while !beams.is_empty() {
let mut new_beams = Vec::with_capacity(beams.capacity()); let mut new_beams = Vec::with_capacity(beams.capacity());
// Row, col and direction // Row, col and direction
for (r,c,d) in beams { for (r, c, d) in beams {
if r >= grid.len() || c >= grid[0].len() { if r >= grid.len() || c >= grid[0].len() {
continue; continue;
} }
@ -68,19 +89,29 @@ impl Day16 {
// Trace the new path in a given direction and draw all of the new beams that come from it. // Trace the new path in a given direction and draw all of the new beams that come from it.
match (grid[r][c], d) { match (grid[r][c], d) {
(b'/', _) => new_beams.push(self.step(r,c,right_lean[d as usize])), (b'/', _) => new_beams.push(self.step(r, c, right_lean[d as usize])),
(b'\\', _) => new_beams.push(self.step(r,c,left_lean[d as usize])), (b'\\', _) => new_beams.push(self.step(r, c, left_lean[d as usize])),
(b'|', Direction::Left|Direction::Right) => new_beams.extend([self.step(r,c,Direction::Up), self.step(r,c,Direction::Down)]), (b'|', Direction::Left | Direction::Right) => new_beams.extend([
(b'-', Direction::Up|Direction::Down) => new_beams.extend([self.step(r,c,Direction::Left), self.step(r,c, Direction::Right)]), self.step(r, c, Direction::Up),
_ => new_beams.push(self.step(r,c,d)), self.step(r, c, Direction::Down),
]),
(b'-', Direction::Up | Direction::Down) => new_beams.extend([
self.step(r, c, Direction::Left),
self.step(r, c, Direction::Right),
]),
_ => new_beams.push(self.step(r, c, d)),
} }
} }
beams = new_beams; beams = new_beams;
} }
// Get the number of 'energised' tiles now that we have finished processing every beam // Get the number of 'energised' tiles now that we have finished processing every beam
energised.iter().flatten().filter(|x| x.iter().any(|&b| b)).count() energised
} .iter()
.flatten()
.filter(|x| x.iter().any(|&b| b))
.count()
}
} }
/// Test from puzzle input /// Test from puzzle input

View File

@ -1,6 +1,6 @@
use super::Solution; use super::Solution;
use crate::utils::Direction; use crate::utils::Direction;
use std::collections::{HashMap, BinaryHeap}; use std::collections::{BinaryHeap, HashMap};
#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct State { struct State {
@ -57,7 +57,17 @@ impl Solution for Day17 {
} }
} }
Ok(Box::new(self.dijkstra((0, 0), (input[0].len() - 1, input.len() - 1), (input[0].len(), input.len()), 1, 3, grid).unwrap())) Ok(Box::new(
self.dijkstra(
(0, 0),
(input[0].len() - 1, input.len() - 1),
(input[0].len(), input.len()),
1,
3,
grid,
)
.unwrap(),
))
} }
fn part2( fn part2(
@ -72,7 +82,17 @@ impl Solution for Day17 {
} }
} }
Ok(Box::new(self.dijkstra((0, 0), (input[0].len() - 1, input.len() - 1), (input[0].len(), input.len()), 4, 10, grid).unwrap())) Ok(Box::new(
self.dijkstra(
(0, 0),
(input[0].len() - 1, input.len() - 1),
(input[0].len(), input.len()),
4,
10,
grid,
)
.unwrap(),
))
} }
fn get_day(&self) -> u8 { fn get_day(&self) -> u8 {
@ -131,7 +151,8 @@ impl Day17 {
dir: d, dir: d,
steps: if d == dir { steps + 1 } else { 1 }, steps: if d == dir { steps + 1 } else { 1 },
}; };
if next.steps > max_step || dist.get(&next.into()).is_some_and(|&c| c <= next.cost) { if next.steps > max_step || dist.get(&next.into()).is_some_and(|&c| c <= next.cost)
{
// For p1 and p2 // For p1 and p2
// Streak gets too long // Streak gets too long
// Or a better solution/path already exists // Or a better solution/path already exists
@ -149,7 +170,12 @@ impl Day17 {
None None
} }
fn neighbours(&self, (x, y): (usize, usize), dir: Direction, (x_len, y_len): (usize, usize)) -> Vec<((usize, usize), Direction)> { fn neighbours(
&self,
(x, y): (usize, usize),
dir: Direction,
(x_len, y_len): (usize, usize),
) -> Vec<((usize, usize), Direction)> {
const fn deltas(x: usize, y: usize) -> [((usize, usize), Direction); 4] { const fn deltas(x: usize, y: usize) -> [((usize, usize), Direction); 4] {
[ [
((x, y.saturating_sub(1)), Direction::Up), ((x, y.saturating_sub(1)), Direction::Up),

View File

@ -61,7 +61,7 @@ pub enum Direction {
Up, Up,
Right, Right,
Down, Down,
Left Left,
} }
impl Direction { impl Direction {
@ -71,7 +71,7 @@ impl Direction {
Direction::Up => Direction::Down, Direction::Up => Direction::Down,
Direction::Down => Direction::Up, Direction::Down => Direction::Up,
Direction::Left => Direction::Right, Direction::Left => Direction::Right,
Direction::Right => Direction::Left Direction::Right => Direction::Left,
} }
} }
} }