Compare commits

..

1 Commits

Author SHA1 Message Date
404ca8bc9f 2023 - Day 24 2023-12-24 23:50:48 +01:00
7 changed files with 76 additions and 1476 deletions

View File

@@ -9,7 +9,6 @@ edition = "2021"
anyhow = "1.0.75" anyhow = "1.0.75"
lazy_static = "1.4.0" lazy_static = "1.4.0"
nalgebra = "0.32.3" nalgebra = "0.32.3"
petgraph = "0.6.4"
regex = "1.10.2" regex = "1.10.2"
[features] [features]

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +0,0 @@
jqt: rhn xhk nvd
rsh: frs pzl lsr
xhk: hfx
cmg: qnr nvd lhk bvb
rhn: xhk bvb hfx
bvb: xhk hfx
pzl: lsr hfx nvd
qnr: nvd
ntq: jqt hfx bvb xhk
nvd: lhk
lsr: lhk
rzs: qnr cmg lsr rsh
frs: qnr lhk lsr

View File

@@ -1,6 +1,9 @@
#![feature(iter_map_windows)] #![feature(iter_map_windows)]
#![feature(test)] #![feature(test)]
use std::{cmp::max, collections::VecDeque}; use std::{
cmp::max,
collections::VecDeque,
};
use anyhow::Result; use anyhow::Result;
use aoc::Solver; use aoc::Solver;

View File

@@ -1,10 +1,6 @@
#![feature(test)] #![feature(test)]
use std::{ use std::{fmt::Display, collections::{hash_map::DefaultHasher, HashMap}, hash::{Hash, Hasher}};
collections::{hash_map::DefaultHasher, HashMap},
fmt::Display,
hash::{Hash, Hasher},
};
use anyhow::Result; use anyhow::Result;
use aoc::Solver; use aoc::Solver;
@@ -120,7 +116,7 @@ fn tilt_east(grid: &mut [Vec<Space>]) {
for line in grid.iter_mut() { for line in grid.iter_mut() {
if line[x] == Space::Round { if line[x] == Space::Round {
let mut new_x = x; let mut new_x = x;
for (xx, space) in line.iter().enumerate().skip(x + 1) { for (xx, space) in line.iter().enumerate().skip(x+1) {
if space == &Space::Empty { if space == &Space::Empty {
new_x = xx new_x = xx
} else { } else {
@@ -144,7 +140,7 @@ fn tilt_south(grid: &mut Vec<Vec<Space>>) {
for x in 0..width { for x in 0..width {
if grid[y][x] == Space::Round { if grid[y][x] == Space::Round {
let mut new_y = y; let mut new_y = y;
for (yy, line) in grid.iter().enumerate().skip(y + 1) { for (yy, line) in grid.iter().enumerate().skip(y+1) {
if line[x] == Space::Empty { if line[x] == Space::Empty {
new_y = yy new_y = yy
} else { } else {

View File

@@ -1,10 +1,10 @@
#![feature(test)] #![feature(test)]
extern crate nalgebra as na; extern crate nalgebra as na;
use std::{collections::HashMap, convert::Infallible, str::FromStr}; use std::{str::FromStr, convert::Infallible, collections::HashMap};
use anyhow::Result; use anyhow::Result;
use aoc::Solver; use aoc::Solver;
use na::{Matrix6, Vector6}; use na::{SMatrix, SVector};
// -- Runners -- // -- Runners --
fn main() -> Result<()> { fn main() -> Result<()> {
@@ -56,7 +56,7 @@ struct Hailstone {
pz: f64, pz: f64,
vx: f64, vx: f64,
vy: f64, vy: f64,
vz: f64, vz: f64
} }
impl Hailstone { impl Hailstone {
@@ -66,11 +66,10 @@ impl Hailstone {
let d = self.vy * other.vx - self.vx * other.vy; let d = self.vy * other.vx - self.vx * other.vy;
let t1 = (other.vy * dx - other.vx * dy) / d; let t1 = (other.vy*dx - other.vx * dy) / d;
let t2 = (self.vy * dx - self.vx * dy) / d; let t2 = (self.vy * dx - self.vx*dy) / d;
if t1.is_sign_negative() || t2.is_sign_negative() { if t1.is_sign_negative() || t2.is_sign_negative() {
// Intersection is in the past
return None; return None;
} }
@@ -78,22 +77,32 @@ impl Hailstone {
let y = self.py + self.vy * t1; let y = self.py + self.vy * t1;
if x.is_infinite() || y.is_infinite() { if x.is_infinite() || y.is_infinite() {
// Paths are parallel
return None; return None;
} }
Some((x, y)) Some((x, y))
} }
fn is_parallel(&self, other: &Hailstone) -> bool {
let dx = self.px - other.px;
let dy = self.py - other.py;
let d = self.vy * other.vx - self.vx * other.vy;
let t1 = (other.vy*dx - other.vx * dy) / d;
let x = self.px + self.vx * t1;
let y = self.py + self.vy * t1;
x.is_infinite() && y.is_infinite()
}
} }
impl FromStr for Hailstone { impl FromStr for Hailstone {
type Err = Infallible; type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<f64> = s let parts: Vec<f64> = s.split([',', '@']).map(|part| part.trim().parse().unwrap()).collect();
.split([',', '@'])
.map(|part| part.trim().parse().unwrap())
.collect();
Ok(Hailstone { Ok(Hailstone {
px: parts[0], px: parts[0],
@@ -113,11 +122,9 @@ fn mode(numbers: &[usize]) -> usize {
*occurrences.entry(value).or_insert(0) += 1; *occurrences.entry(value).or_insert(0) += 1;
} }
occurrences println!("{occurrences:?}");
.into_iter()
.max_by_key(|&(_, count)| count) occurrences.into_iter().max_by_key(|&(_, count)| count).map(|(value, _)| value).unwrap()
.map(|(value, _)| value)
.unwrap()
} }
// -- Solution -- // -- Solution --
@@ -139,19 +146,11 @@ impl aoc::Solver for Day {
200000000000000.0..=400000000000000.0 200000000000000.0..=400000000000000.0
}; };
hailstones hailstones.iter().enumerate().flat_map(|(index_a, a)| {
.iter() hailstones.iter().enumerate().filter(|(index_b, _)| index_b < &index_a).filter_map(|(_, b)| {
.enumerate() a.intersect_2d(b)
.flat_map(|(index_a, a)| { }).collect::<Vec<_>>()
hailstones }).filter(|&(x, y)| range.contains(&x) && range.contains(&y)).count()
.iter()
.enumerate()
.filter(|(index_b, _)| index_b < &index_a)
.filter_map(|(_, b)| a.intersect_2d(b))
.collect::<Vec<_>>()
})
.filter(|&(x, y)| range.contains(&x) && range.contains(&y))
.count()
} }
fn part2(input: &str) -> Self::Output2 { fn part2(input: &str) -> Self::Output2 {
@@ -181,8 +180,7 @@ impl aoc::Solver for Day {
let j = 1; let j = 1;
// Due to numerical instability we run this with several different options for the third // Due to numerical instability we run this with several different options for the third
// hailstone // hailstone
let solutions: Vec<_> = (2..h.len()) let solutions: Vec<_> = (2..h.len()).map(|k| {
.map(|k| {
// Constant in the matrix // Constant in the matrix
let c1 = h[i].vz - h[j].vz; let c1 = h[i].vz - h[j].vz;
let c2 = h[i].py - h[j].py; let c2 = h[i].py - h[j].py;
@@ -199,35 +197,35 @@ impl aoc::Solver for Day {
let c12 = h[k].px - h[i].px; let c12 = h[k].px - h[i].px;
// Setup the matrix // Setup the matrix
let matrix = Matrix6::new( let matrix = SMatrix::<f64, 6, 6>::new(
0.0, c1, c3, 0.0, c4, c2, -c1, 0.0, c5, -c4, 0.0, c6, -c3, -c5, 0.0, -c2, -c6, 0.0, c1, c3, 0.0, c4, c2,
0.0, 0.0, c7, c9, 0.0, c10, c8, -c7, 0.0, c11, -c10, 0.0, c12, -c9, -c11, 0.0, -c1, 0.0, c5, -c4, 0.0, c6,
-c8, -c12, 0.0, -c3, -c5, 0.0, -c2, -c6, 0.0,
0.0, c7, c9, 0.0, c10, c8,
-c7, 0.0, c11, -c10, 0.0, c12,
-c9, -c11, 0.0, -c8, -c12, 0.0
); );
// Get the inverse of the matrix
let inverse = matrix.try_inverse().unwrap();
// Constant on the rhs // Constant on the rhs
let k1 = let k1 = h[i].py*h[i].vz - h[j].py*h[j].vz + h[j].pz*h[j].vy - h[i].pz*h[i].vy;
h[i].py * h[i].vz - h[j].py * h[j].vz + h[j].pz * h[j].vy - h[i].pz * h[i].vy; let k2 = h[i].pz*h[i].vx - h[j].pz*h[j].vx + h[j].px*h[j].vz - h[i].px*h[i].vz;
let k2 = let k3 = h[i].px*h[i].vy - h[j].px*h[j].vy + h[j].py*h[j].vx - h[i].py*h[i].vx;
h[i].pz * h[i].vx - h[j].pz * h[j].vx + h[j].px * h[j].vz - h[i].px * h[i].vz; let k4 = h[i].py*h[i].vz - h[k].py*h[k].vz + h[k].pz*h[k].vy - h[i].pz*h[i].vy;
let k3 = let k5 = h[i].pz*h[i].vx - h[k].pz*h[k].vx + h[k].px*h[k].vz - h[i].px*h[i].vz;
h[i].px * h[i].vy - h[j].px * h[j].vy + h[j].py * h[j].vx - h[i].py * h[i].vx; let k6 = h[i].px*h[i].vy - h[k].px*h[k].vy + h[k].py*h[k].vx - h[i].py*h[i].vx;
let k4 =
h[i].py * h[i].vz - h[k].py * h[k].vz + h[k].pz * h[k].vy - h[i].pz * h[i].vy;
let k5 =
h[i].pz * h[i].vx - h[k].pz * h[k].vx + h[k].px * h[k].vz - h[i].px * h[i].vz;
let k6 =
h[i].px * h[i].vy - h[k].px * h[k].vy + h[k].py * h[k].vx - h[i].py * h[i].vx;
// Put them into a vector // Put them into a vector
let k = Vector6::new(k1, k2, k3, k4, k5, k6); let k = SVector::<f64, 6>::new(k1, k2, k3, k4, k5, k6);
let solution = matrix.lu().solve(&k).unwrap(); // Calclate the solution
let solution = inverse * k;
// The sum of all elements of the starting position is the answer // The sum of all elements of the starting position is the answer
(solution[0] + solution[1] + solution[2]).round() as usize (solution[0] + solution[1] + solution[2]).round() as usize
}) }).collect();
.collect();
// The most common solution is the actual solution // The most common solution is the actual solution
mode(&solutions) mode(&solutions)

View File

@@ -1,172 +0,0 @@
#![feature(test)]
#![feature(iter_map_windows)]
use std::collections::{HashMap, HashSet, VecDeque};
use anyhow::Result;
use aoc::Solver;
use petgraph::{
algo::{condensation, has_path_connecting},
graphmap::{GraphMap, UnGraphMap},
visit::IntoNodeReferences,
Undirected,
};
// -- Runners --
fn main() -> Result<()> {
Day::solve()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_test1() -> Result<()> {
Day::test(Day::part1, "test-1", 54)
}
#[test]
fn part1_solution() -> Result<()> {
Day::test(Day::part1, "input", 552695)
}
// Benchmarks
extern crate test;
#[bench]
#[ignore]
fn part1_bench(b: &mut test::Bencher) {
Day::benchmark(Day::part1, b)
}
#[bench]
#[ignore]
fn part2_bench(b: &mut test::Bencher) {
Day::benchmark(Day::part2, b)
}
}
// Totally copied this from: https://github.com/Zemogus/AOC-2023/blob/328dc6618f3a360c3d3851ad1b10513a6c133336/src/day25.rs
// For some reason the graph library has no dijkstra that returns the actual path
fn find_shortest_path<'a>(
graph: &GraphMap<&'a str, (), Undirected>,
start: &'a str,
end: &'a str,
) -> Option<Vec<&'a str>> {
let mut queue = VecDeque::new();
let mut visited = HashSet::new();
let mut parents = HashMap::new();
queue.push_back(start);
while let Some(node) = queue.pop_front() {
// Already visited this node
if !visited.insert(node) {
continue;
}
// Reached the destination
if node == end {
break;
}
for neighbour in graph.neighbors(node) {
if !visited.contains(neighbour) {
parents.insert(neighbour, node);
queue.push_back(neighbour);
}
}
}
let mut path = Vec::new();
let mut node = end;
while node != start {
path.push(node);
if let Some(parent) = parents.get(&node) {
node = parent;
} else {
return None;
}
}
path.push(start);
Some(path)
}
// -- Solution --
pub struct Day;
impl aoc::Solver for Day {
type Output1 = usize;
type Output2 = usize;
fn day() -> u8 {
25
}
fn part1(input: &str) -> Self::Output1 {
// Create a list of all edges
let edges: Vec<_> = input
.lines()
.flat_map(|line| {
let (a, rest) = line.split_once(": ").unwrap();
rest.split(' ').map(|b| (a, b)).collect::<Vec<_>>()
})
.collect();
// Create a graph from all the edges
let graph = UnGraphMap::<_, ()>::from_edges(edges);
// Take a node as the starting point
let start = graph.nodes().next().unwrap();
// Loop over all other nodes
for end in graph.nodes() {
// Make a copy of the graph so we can modify it and undo changes later
let mut graph = graph.clone();
if start == end {
continue;
}
// If the two nodes are on the same side there should be more then three paths
// connecting the nodes together
// At least I think???
// This solution worked, so ¯\_(ツ)_/¯
for _ in 0..3 {
// Find the current shortest path
let path = find_shortest_path(&graph, start, end).unwrap();
// Remove the path
for slice in path.windows(2) {
match slice {
[a, b] => graph.remove_edge(a, b),
_ => unreachable!(
"There should be three paths connecting all the nodes together"
),
};
}
}
// If there is no path connecting the two nodes we have removed the three edges
// connecting the two halves
if !has_path_connecting(&graph, start, end, None) {
// Condense the graph, creates a new graph where each node contains all nodes that
// where connected in the input node
let condensed = condensation(graph.into_graph::<usize>(), false);
// The should give us two nodes each containing all the nodes in their respective
// half if we split the graph
if condensed.node_count() != 2 {
continue;
}
// Multiply the size of each of the halves together giving the final solution
return condensed
.node_references()
.fold(1, |acc, (_, nodes)| acc * nodes.len());
}
}
unreachable!("No solution found");
}
fn part2(_input: &str) -> Self::Output2 {
0
}
}