Import aoc2025 history into 2025/
git-subtree-dir: 2025 git-subtree-mainline:cceb6f232egit-subtree-split:0446debff4
This commit is contained in:
commit
70a284ca0f
39 files changed
+5184
No files matched your search
@@ -0,0 +1,98 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
|
||||
// PROBLEM 1 solution
|
||||
#[aoc(day1, part1)]
|
||||
pub fn part1(input: &str) -> u64 {
|
||||
let mut val = 50u64;
|
||||
let mut pass = 0u64;
|
||||
let mod_val = 100;
|
||||
for line in input.lines() {
|
||||
let line = line.trim();
|
||||
let (sign, num) = line.split_at(1);
|
||||
let num_val = num.parse::<u64>().unwrap();
|
||||
|
||||
let add_val = match sign.as_bytes()[0] {
|
||||
b'R' => num_val,
|
||||
b'L' => mod_val - (num_val % mod_val),
|
||||
c => panic!("Invalid direction {c}"),
|
||||
};
|
||||
val = (val + add_val) % mod_val;
|
||||
if val == 0 {
|
||||
pass += 1
|
||||
}
|
||||
}
|
||||
pass
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
|
||||
fn advance<const N: i64>(mut start: i64, mut n: i64) -> (i64, i64) {
|
||||
let mut zero_crossings = 0;
|
||||
while n != 0 {
|
||||
if n > 0 {
|
||||
start += 1;
|
||||
if start == 100 {
|
||||
start = 0;
|
||||
zero_crossings += 1;
|
||||
}
|
||||
n -= 1
|
||||
} else {
|
||||
start -= 1;
|
||||
if start == 0 {
|
||||
zero_crossings += 1;
|
||||
}
|
||||
if start == -1 {
|
||||
start = 99;
|
||||
}
|
||||
n += 1
|
||||
}
|
||||
}
|
||||
(start, zero_crossings)
|
||||
}
|
||||
|
||||
#[aoc(day1, part2)]
|
||||
pub fn part2(input: &str) -> i64 {
|
||||
let mut val = 50;
|
||||
let mut pass = 0i64;
|
||||
|
||||
for line in input.lines() {
|
||||
let line = line.trim();
|
||||
let (sign, num) = line.split_at(1);
|
||||
let num_val = num.parse::<i64>().unwrap();
|
||||
|
||||
let (new_val, add_pass) = match sign.as_bytes()[0] {
|
||||
b'R' => advance::<100>(val, num_val),
|
||||
b'L' => advance::<100>(val, -num_val),
|
||||
c => panic!("Invalid direction {c}"),
|
||||
};
|
||||
val = new_val;
|
||||
pass += add_pass;
|
||||
}
|
||||
pass
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::day1::*;
|
||||
|
||||
const EXAMPLE: &str = "L68
|
||||
L30
|
||||
R48
|
||||
L5
|
||||
R60
|
||||
L55
|
||||
L1
|
||||
L99
|
||||
R14
|
||||
L82";
|
||||
|
||||
#[test]
|
||||
fn problem1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn problem2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
use std::{
|
||||
collections::{BinaryHeap, VecDeque},
|
||||
hash::Hash,
|
||||
iter::{repeat, repeat_n},
|
||||
};
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use itertools::Itertools;
|
||||
use regex::Regex;
|
||||
use wide::{CmpGt, i16x16};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct MachineDefinition {
|
||||
desired: Vec<bool>,
|
||||
buttons: Vec<Vec<usize>>,
|
||||
buttons2: Vec<i16x16>,
|
||||
buttons_max: i16x16,
|
||||
joltages: i16x16,
|
||||
}
|
||||
|
||||
impl MachineDefinition {
|
||||
fn create<'a>(&'a self) -> Machine<'a> {
|
||||
Machine {
|
||||
d: self,
|
||||
lights: Vec::from_iter(repeat_n(false, self.desired.len())),
|
||||
}
|
||||
}
|
||||
|
||||
fn create2<'a>(&'a self) -> JoltMachine<'a> {
|
||||
JoltMachine {
|
||||
d: self,
|
||||
joltages: i16x16::splat(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for MachineDefinition {
|
||||
fn from(value: &str) -> Self {
|
||||
let parse_re = Regex::new(
|
||||
r##"\[(?<desired>[.#]+)\] (?<buttons>(\([0-9,]+\) ?)+) \{(?<joltages>[0-9,]+)\}"##,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let parts = parse_re.captures(value).unwrap();
|
||||
let joltages: [i16; 16] = parts["joltages"]
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap())
|
||||
.chain(repeat(0))
|
||||
.take(16)
|
||||
.collect_array()
|
||||
.unwrap();
|
||||
|
||||
let buttons = parts["buttons"]
|
||||
.split_ascii_whitespace()
|
||||
.map(|s| {
|
||||
s[1..s.len() - 1]
|
||||
.split(',')
|
||||
.map(|n| n.parse().unwrap())
|
||||
.collect()
|
||||
})
|
||||
.sorted_unstable_by_key(|s: &Vec<usize>| s.len())
|
||||
.rev()
|
||||
.collect_vec();
|
||||
|
||||
let mut buttons2 = Vec::new();
|
||||
let mut buttons_max = [0i16; 16];
|
||||
|
||||
for (i, b) in buttons.iter().enumerate() {
|
||||
let mut but = [0i16; 16];
|
||||
for i in b {
|
||||
but[*i] = 1;
|
||||
}
|
||||
buttons2.push(i16x16::new(but));
|
||||
|
||||
// find the joltage this button affects with the lowest value
|
||||
// it is the max number of presses for this button
|
||||
buttons_max[i] = b.iter().map(|idx| joltages[*idx]).min().unwrap();
|
||||
}
|
||||
|
||||
MachineDefinition {
|
||||
desired: parts["desired"].chars().map(|c| c == '#').collect(),
|
||||
buttons: buttons,
|
||||
buttons2: buttons2,
|
||||
buttons_max: i16x16::new(buttons_max),
|
||||
joltages: i16x16::new(joltages),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Machine<'a> {
|
||||
d: &'a MachineDefinition,
|
||||
lights: Vec<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct JoltMachine<'a> {
|
||||
d: &'a MachineDefinition,
|
||||
joltages: i16x16,
|
||||
}
|
||||
|
||||
impl<'a> Machine<'a> {
|
||||
/// Get the state after pressing `button`, returns None if the state is as desired.
|
||||
fn press(&self, button: usize) -> Option<Self> {
|
||||
let mut new_state = self.lights.clone();
|
||||
for light in &self.d.buttons[button] {
|
||||
new_state[*light] = !new_state[*light];
|
||||
}
|
||||
if new_state == self.d.desired {
|
||||
None
|
||||
} else {
|
||||
Some(Machine {
|
||||
d: self.d,
|
||||
lights: new_state,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// Get the possible states from the current position
|
||||
fn next_states(&self) -> Vec<(usize, Option<Self>)> {
|
||||
self.d
|
||||
.buttons
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, _but)| (i, self.press(i)))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> JoltMachine<'a> {
|
||||
fn press_jolts(&self, button: usize, presses: &i16x16) -> (i16x16, Option<Self>) {
|
||||
// let mut new_joltage = self.joltages.clone();
|
||||
// // for jolt in &self.d.buttons[button] {
|
||||
// // new_joltage[*jolt] += 1;
|
||||
// // }
|
||||
let new_joltage = self.joltages + self.d.buttons2[button];
|
||||
let mut new_presses = presses.clone();
|
||||
new_presses.as_mut_array()[button] += 1;
|
||||
if new_joltage == self.d.joltages {
|
||||
(new_presses, None)
|
||||
} else {
|
||||
(
|
||||
new_presses,
|
||||
Some(Self {
|
||||
d: self.d,
|
||||
joltages: new_joltage,
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn next_states_jolt(&self, presses: &i16x16) -> Vec<(i16x16, Option<Self>)> {
|
||||
self.d
|
||||
.buttons
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, _but)| self.press_jolts(i, &presses))
|
||||
// .inspect(|(p, o)| println!(" {p:?} {o:?}\n"))
|
||||
// joltages monotonically increase, so cull any where a joltage is higher than needed
|
||||
.filter(|(presses, candidate)| {
|
||||
!presses.simd_gt(self.d.buttons_max).any()
|
||||
&& candidate.as_ref().is_none_or(|c| {
|
||||
!c.joltages.simd_gt(self.d.joltages).any()
|
||||
// !c.joltages
|
||||
// .iter()
|
||||
// .zip(self.d.joltages.iter())
|
||||
// .any(|(candidate, expected)| candidate > expected)
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PressSet<'a> {
|
||||
machine: Machine<'a>,
|
||||
presses: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PressSet2<'a> {
|
||||
machine: JoltMachine<'a>,
|
||||
presses: i16x16,
|
||||
}
|
||||
|
||||
// NOTE: All compares are reversed so our max heap becomes a min heap
|
||||
impl<'a> Eq for PressSet<'a> {}
|
||||
impl<'a> Eq for PressSet2<'a> {}
|
||||
|
||||
impl<'a> PartialEq for PressSet<'a> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
other.presses.eq(&self.presses)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> PartialEq for PressSet2<'a> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
other.presses.eq(&self.presses)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> PartialOrd for PressSet<'a> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> PartialOrd for PressSet2<'a> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Ord for PressSet<'a> {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
other.presses.cmp(&self.presses)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Ord for PressSet2<'a> {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
other.presses.reduce_add().cmp(&self.presses.reduce_add())
|
||||
}
|
||||
}
|
||||
|
||||
fn find_best(md: &MachineDefinition) -> usize {
|
||||
let m = md.create();
|
||||
let mut to_check = BinaryHeap::new();
|
||||
to_check.push(PressSet {
|
||||
presses: 0,
|
||||
machine: m,
|
||||
});
|
||||
|
||||
while let Some(candidate) = to_check.pop() {
|
||||
let cm = candidate.machine.clone();
|
||||
for next in cm.next_states() {
|
||||
let presses = candidate.presses + 1;
|
||||
if let Some(new_m) = next.1 {
|
||||
to_check.push(PressSet {
|
||||
presses,
|
||||
machine: new_m.clone(),
|
||||
})
|
||||
} else {
|
||||
return presses;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!()
|
||||
}
|
||||
|
||||
fn find_best_jolts(md: &MachineDefinition) -> usize {
|
||||
let m = md.create2();
|
||||
let mut to_check = VecDeque::new();
|
||||
to_check.push_back(PressSet2 {
|
||||
presses: i16x16::splat(0),
|
||||
machine: m,
|
||||
});
|
||||
|
||||
let mut pb = ProgressBar::no_length()
|
||||
.with_style(
|
||||
ProgressStyle::with_template(
|
||||
"[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}",
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.with_finish(indicatif::ProgressFinish::AndLeave);
|
||||
|
||||
while let Some(candidate) = to_check.pop_front() {
|
||||
pb.inc(1);
|
||||
pb.set_length(to_check.len() as u64);
|
||||
let cm = candidate.machine.clone();
|
||||
for (presses, next) in cm.next_states_jolt(&candidate.presses) {
|
||||
if let Some(new_m) = next {
|
||||
to_check.push_back(PressSet2 {
|
||||
presses,
|
||||
machine: new_m.clone(),
|
||||
})
|
||||
} else {
|
||||
return presses.reduce_add() as usize;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!()
|
||||
}
|
||||
|
||||
#[aoc_generator(day10)]
|
||||
fn parse(input: &str) -> Vec<MachineDefinition> {
|
||||
input.lines().map(|l| l.into()).collect()
|
||||
}
|
||||
|
||||
#[aoc(day10, part1)]
|
||||
fn part1(input: &[MachineDefinition]) -> u64 {
|
||||
input
|
||||
.iter()
|
||||
.map(find_best)
|
||||
// .inspect(|sol| println!(" [{sol:?}]"))
|
||||
.map(|sol| sol as u64)
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[aoc(day10, part2)]
|
||||
fn part2(input: &[MachineDefinition]) -> u64 {
|
||||
input
|
||||
.iter()
|
||||
.map(find_best_jolts)
|
||||
.map(|sol| sol as u64)
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rstest::rstest;
|
||||
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "[.##.] (3) (1,3) (2) (2,3) (0,2) (0,1) {3,5,4,7}
|
||||
[...#.] (0,2,3,4) (2,3) (0,4) (0,1,2) (1,2,3,4) {7,5,12,7,2}
|
||||
[.###.#] (0,1,2,3,4) (0,3,4) (0,1,2,4,5) (1,2) {10,11,11,5,10,5}";
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE, 7)]
|
||||
fn part1_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part1(&parse(input)), expected);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE, 33)]
|
||||
fn part2_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part2(&parse(input)), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
||||
|
||||
type Edges = FxHashMap<String, Vec<String>>;
|
||||
|
||||
#[aoc_generator(day11)]
|
||||
fn parse(input: &str) -> Edges {
|
||||
let mut edges: Edges = FxHashMap::default();
|
||||
for l in input.lines() {
|
||||
let (k, rest) = l.split_once(": ").unwrap();
|
||||
for v in rest.split_ascii_whitespace() {
|
||||
edges.entry(k.to_string()).or_default().push(v.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
edges
|
||||
}
|
||||
|
||||
fn find_path(cur: &str, goal: &str, edges: &Edges) -> u64 {
|
||||
if cur == goal {
|
||||
return 1;
|
||||
}
|
||||
if let Some(nexts) = edges.get(cur) {
|
||||
nexts.iter().map(|n| find_path(n, goal, edges)).sum()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_paths<'a>(
|
||||
cur: &'a str,
|
||||
edges: &'a Edges,
|
||||
mut reachable: FxHashSet<&'a str>,
|
||||
) -> FxHashSet<&'a str> {
|
||||
reachable.insert(cur);
|
||||
if let Some(nexts) = edges.get(cur) {
|
||||
for n in nexts {
|
||||
if !reachable.contains(&n.as_str()) {
|
||||
reachable = mark_paths(n, edges, reachable);
|
||||
}
|
||||
}
|
||||
}
|
||||
reachable
|
||||
}
|
||||
|
||||
fn count_paths_impl<'a>(
|
||||
cur: &'a str,
|
||||
goal: &str,
|
||||
edges: &'a Edges,
|
||||
memo: &mut FxHashMap<&'a str, u64>,
|
||||
) -> u64 {
|
||||
if cur == goal {
|
||||
return 1;
|
||||
}
|
||||
if let Some(v) = memo.get(cur) {
|
||||
return *v;
|
||||
}
|
||||
|
||||
if let Some(nexts) = edges.get(cur) {
|
||||
let ret = nexts
|
||||
.iter()
|
||||
.map(|n| count_paths_impl(n, goal, edges, memo))
|
||||
.sum();
|
||||
memo.insert(cur, ret);
|
||||
ret
|
||||
} else {
|
||||
memo.insert(cur, 0);
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn count_paths(cur: &str, goal: &str, edges: &Edges) -> u64 {
|
||||
let mut cache = FxHashMap::default();
|
||||
count_paths_impl(cur, goal, edges, &mut cache)
|
||||
}
|
||||
|
||||
#[aoc(day11, part1, NaiveDfs)]
|
||||
fn part1(fwd: &Edges) -> u64 {
|
||||
find_path("you", "out", fwd)
|
||||
}
|
||||
|
||||
#[aoc(day11, part1, MemoDfs)]
|
||||
fn part1_memo(fwd: &Edges) -> u64 {
|
||||
count_paths("you", "out", fwd)
|
||||
}
|
||||
|
||||
#[aoc(day11, part2, MemoDfs)]
|
||||
fn part2_memo(edges: &Edges) -> u64 {
|
||||
// we assume all valid paths reach svr->fft->dac->out in that order. this holds on the example and the input.
|
||||
// to handle both possible orderings, we need to sum paths fft->dac and dac->fft, and then partition the graph
|
||||
// (just remove the node) at dac & fft before computing the sum of dac->out and fft->out.
|
||||
//
|
||||
// this is our performance implementation though and it's faster to not do that work. we do the posterity for the
|
||||
// naive solution
|
||||
count_paths("svr", "fft", edges)
|
||||
* count_paths("fft", "dac", edges)
|
||||
* count_paths("dac", "out", edges)
|
||||
}
|
||||
|
||||
#[aoc(day11, part2, NaiveDfs)]
|
||||
fn part2(edges: &Edges) -> u64 {
|
||||
let mut rev = Edges::from_iter(edges.keys().map(|k| (k.to_owned(), vec![])));
|
||||
for (from, tos) in edges {
|
||||
for to in tos {
|
||||
rev.entry(to.to_owned()).or_default().push(from.to_owned());
|
||||
}
|
||||
}
|
||||
let mut reachable_dac = mark_paths("dac", edges, FxHashSet::default());
|
||||
reachable_dac = mark_paths("dac", &rev, reachable_dac);
|
||||
let mut reachable_fft = mark_paths("fft", edges, FxHashSet::default());
|
||||
reachable_fft = mark_paths("fft", &rev, reachable_fft);
|
||||
|
||||
let reachable: FxHashSet<&str> = reachable_dac
|
||||
.intersection(&reachable_fft)
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
let unreachable: FxHashSet<&str> = FxHashSet::from_iter(edges.keys().map(|k| k.as_str()))
|
||||
.difference(&reachable)
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
let mut reachable_edges = edges.clone();
|
||||
|
||||
for k in &unreachable {
|
||||
reachable_edges.remove(*k);
|
||||
}
|
||||
for (_k, v) in reachable_edges.iter_mut() {
|
||||
for ur in &unreachable {
|
||||
if let Some(idx) = v.iter().position(|s| s == ur) {
|
||||
v.remove(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A real graph structure would probably notice that the graphs get split here
|
||||
let mut reachable_edges_excl_fft = reachable_edges.clone();
|
||||
reachable_edges_excl_fft.remove("fft");
|
||||
let mut reachable_edges_excl_dac = reachable_edges.clone();
|
||||
reachable_edges_excl_dac.remove("dac");
|
||||
|
||||
find_path("svr", "fft", &reachable_edges)
|
||||
// only svr->fft->dac->out paths appear in my input and in the example, but include the dac->fft ordering
|
||||
// as well, for posterity. It ~doubles runtime.
|
||||
* (find_path("fft", "dac", &reachable_edges) + find_path("dac", "fft", &reachable_edges))
|
||||
* (find_path("dac", "out", &reachable_edges_excl_fft) + find_path("fft", "out", &reachable_edges_excl_dac))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rstest::rstest;
|
||||
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "aaa: you hhh
|
||||
you: bbb ccc
|
||||
bbb: ddd eee
|
||||
ccc: ddd eee fff
|
||||
ddd: ggg
|
||||
eee: out
|
||||
fff: out
|
||||
ggg: out
|
||||
hhh: ccc fff iii
|
||||
iii: out";
|
||||
|
||||
const EXAMPLE2: &str = "svr: aaa bbb
|
||||
aaa: fft
|
||||
fft: ccc
|
||||
bbb: tty
|
||||
tty: ccc
|
||||
ccc: ddd eee
|
||||
ddd: hub
|
||||
hub: fff
|
||||
eee: dac
|
||||
dac: fff
|
||||
fff: ggg hhh
|
||||
ggg: out
|
||||
hhh: out";
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE, 5)]
|
||||
fn part1_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part1(&parse(input)), expected);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE, 5)]
|
||||
fn part1_memo_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part1_memo(&parse(input)), expected);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE2, 2)]
|
||||
fn part2_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part2(&parse(input)), expected);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE2, 2)]
|
||||
fn part2_memo_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part2_memo(&parse(input)), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use grid::{Coord2d, Grid, MirrorAxis};
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use itertools::Itertools;
|
||||
use rayon::iter::IntoParallelRefIterator;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Display;
|
||||
use std::iter::repeat_n;
|
||||
|
||||
type CellType = bool;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PresentShape {
|
||||
variants: Vec<Grid<CellType>>,
|
||||
}
|
||||
|
||||
impl From<&str> for PresentShape {
|
||||
fn from(value: &str) -> Self {
|
||||
let (_idx, rest) = value.split_once(":\n").unwrap();
|
||||
|
||||
let shape_raw: Grid<u8> = rest.parse().unwrap();
|
||||
let mut shape: Grid<CellType> = shape_raw.same_shape(false);
|
||||
for pos in shape_raw.find_all(&b'#') {
|
||||
shape.set(&pos, true);
|
||||
}
|
||||
|
||||
Self {
|
||||
variants: (0..4)
|
||||
.map(|rot| shape.rotated(rot))
|
||||
.chain([MirrorAxis::X, MirrorAxis::Y].map(|axis| shape.mirrored(axis)))
|
||||
.unique()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for PresentShape {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!("{}", self.variants[0]))
|
||||
}
|
||||
}
|
||||
|
||||
impl PresentShape {
|
||||
fn popcount(&self) -> u64 {
|
||||
self.variants[0].count(&true) as u64
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Present {
|
||||
shape: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ChristmasTree {
|
||||
area: Grid<CellType>,
|
||||
presents: Vec<Present>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PresentsProblem {
|
||||
trees: Vec<ChristmasTree>,
|
||||
shapes: Vec<PresentShape>,
|
||||
}
|
||||
|
||||
#[aoc_generator(day12)]
|
||||
fn parse(input: &str) -> PresentsProblem {
|
||||
let mut parts = input.split("\n\n").collect_vec();
|
||||
let trees_s = parts.pop().unwrap();
|
||||
|
||||
let shapes: Vec<PresentShape> = parts.into_iter().map(|p| p.into()).collect();
|
||||
let mut trees = Vec::new();
|
||||
|
||||
for l in trees_s.lines() {
|
||||
let (d, el) = l.split_once(": ").unwrap();
|
||||
let (w, h) = d.split_once('x').unwrap();
|
||||
let present_counts: Vec<usize> = el
|
||||
.split_ascii_whitespace()
|
||||
.map(|count| count.parse().unwrap())
|
||||
.collect_vec();
|
||||
let presents = present_counts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, count)| repeat_n(Present { shape: i }, *count))
|
||||
.collect();
|
||||
trees.push(ChristmasTree {
|
||||
area: Grid::with_shape(w.parse().unwrap(), h.parse().unwrap(), false),
|
||||
presents,
|
||||
});
|
||||
}
|
||||
|
||||
PresentsProblem { trees, shapes }
|
||||
}
|
||||
|
||||
// place b on a and test if any # overlap any non-.
|
||||
// fn overlaps(a: &Grid<CellType>, b: &Grid<CellType>, p: &Coord2d) -> bool {
|
||||
// b.find_all(&true)
|
||||
// .any(|c| a.get(&(c + p)).is_some_and(|c| *c))
|
||||
// }
|
||||
|
||||
impl PresentsProblem {
|
||||
fn place_shape(
|
||||
&self,
|
||||
mut t: ChristmasTree,
|
||||
idx: usize,
|
||||
pos: Coord2d,
|
||||
variant: usize,
|
||||
) -> Option<ChristmasTree> {
|
||||
let variant = &self.shapes[t.presents[idx].shape].variants[variant];
|
||||
|
||||
for xy in variant.find_all(&true) {
|
||||
if let Some(was) = t.area.set(&(pos + &(xy)), true)
|
||||
&& was
|
||||
{
|
||||
// overlapped
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(t)
|
||||
}
|
||||
|
||||
fn place_next(
|
||||
&self,
|
||||
t: ChristmasTree,
|
||||
cur: usize,
|
||||
cache: &mut HashSet<(usize, Grid<CellType>)>, // impossible shapes
|
||||
) -> bool {
|
||||
if cur == t.presents.len() {
|
||||
// done
|
||||
return true;
|
||||
}
|
||||
if cache.contains(&(cur, t.area.clone())) {
|
||||
// doomed
|
||||
return false;
|
||||
}
|
||||
let variants = &self.shapes[t.presents[cur].shape].variants;
|
||||
for (i, _v) in variants.iter().enumerate() {
|
||||
for y in 0..&t.area.height() - 2 {
|
||||
for x in 0..&t.area.width() - 2 {
|
||||
if let Some(new_t) = self.place_shape(
|
||||
t.clone(),
|
||||
cur,
|
||||
Coord2d {
|
||||
x: x as i64,
|
||||
y: y as i64,
|
||||
},
|
||||
i,
|
||||
) {
|
||||
if self.place_next(new_t, cur + 1, cache) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cache.insert((cur, t.area.clone()));
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc(day12, part1)]
|
||||
fn part1(input: &PresentsProblem) -> u64 {
|
||||
let input = input.clone();
|
||||
let mut count = 0;
|
||||
|
||||
for (i, t) in input.trees.iter().enumerate() {
|
||||
let timer = std::time::Instant::now();
|
||||
let area = (t.area.width() * t.area.height()) as u64;
|
||||
let (occupied_area, present_count) = t
|
||||
.presents
|
||||
.iter()
|
||||
.map(|p| (input.shapes[p.shape].popcount(), 1))
|
||||
.reduce(|(o_a, pc_a), (o_b, pc_b)| (o_a + o_b, pc_a + pc_b))
|
||||
.unwrap();
|
||||
if occupied_area > area {
|
||||
let elapsed = timer.elapsed();
|
||||
println!("{i} - CULLED IMPOSSIBLE ({}ms)", elapsed.as_millis());
|
||||
// definitely impossible
|
||||
continue;
|
||||
}
|
||||
let available_3x3s = (t.area.width() / 3) * (t.area.height() / 3);
|
||||
if available_3x3s >= present_count {
|
||||
let elapsed = timer.elapsed();
|
||||
println!("{i} - CULLED POSSIBLE ({}ms)", elapsed.as_millis());
|
||||
|
||||
// definitely_possible
|
||||
count += 1;
|
||||
continue;
|
||||
}
|
||||
if input.place_next(t.clone(), 0, &mut HashSet::new()) {
|
||||
let elapsed = timer.elapsed();
|
||||
println!("{i} - SOLVED POSSIBLE ({}ms)", elapsed.as_millis());
|
||||
count += 1;
|
||||
continue;
|
||||
}
|
||||
let elapsed = timer.elapsed();
|
||||
println!("{i} - SOLVED IMPOSSIBLE ({}ms)", elapsed.as_millis());
|
||||
}
|
||||
|
||||
count
|
||||
}
|
||||
|
||||
#[aoc(day12, part2)]
|
||||
fn part2(_input: &PresentsProblem) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rstest::rstest;
|
||||
|
||||
const EXAMPLE: &str = "0:
|
||||
###
|
||||
##.
|
||||
##.
|
||||
|
||||
1:
|
||||
###
|
||||
##.
|
||||
.##
|
||||
|
||||
2:
|
||||
.##
|
||||
###
|
||||
##.
|
||||
|
||||
3:
|
||||
##.
|
||||
###
|
||||
##.
|
||||
|
||||
4:
|
||||
###
|
||||
#..
|
||||
###
|
||||
|
||||
5:
|
||||
###
|
||||
.#.
|
||||
###
|
||||
|
||||
4x4: 0 0 0 0 2 0
|
||||
12x5: 1 0 1 0 2 2
|
||||
12x5: 1 0 1 0 3 2";
|
||||
|
||||
const EXAMPLE2: &str = "0:
|
||||
.#.
|
||||
###
|
||||
.#.
|
||||
|
||||
1:
|
||||
###
|
||||
#..
|
||||
###
|
||||
|
||||
2:
|
||||
###
|
||||
#.#
|
||||
###
|
||||
|
||||
7x3: 1 2 0
|
||||
17x17: 37 0 0
|
||||
7x7: 1 0 4
|
||||
7x7: 0 0 5";
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE, 2)]
|
||||
#[case(EXAMPLE2, 3)]
|
||||
fn part1_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part1(&parse(input)), expected);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE, 0)]
|
||||
fn part2_example(#[case] input: &str, #[case] expected: u64) {
|
||||
assert_eq!(part2(&parse(input)), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use itertools::Itertools;
|
||||
use misc::POW10;
|
||||
use std::cmp::{max, min};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
#[aoc_generator(day2)]
|
||||
fn parse(input: &str) -> Vec<RangeInclusive<u64>> {
|
||||
input
|
||||
.split(',')
|
||||
.map(|r| r.split_once('-').unwrap())
|
||||
.map(|(start, end)| RangeInclusive::new(start.parse().unwrap(), end.parse().unwrap()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[aoc(day2, part1, Brute)]
|
||||
fn part1(input: &[RangeInclusive<u64>]) -> u64 {
|
||||
let mut invalid_sum = 0;
|
||||
|
||||
for r in input {
|
||||
for product in r.clone() {
|
||||
let prod_s = product.to_string();
|
||||
if !prod_s.len().is_multiple_of(2) {
|
||||
continue;
|
||||
}
|
||||
let (left, right) = prod_s.split_at(prod_s.len() / 2);
|
||||
if left == right {
|
||||
invalid_sum += product
|
||||
}
|
||||
}
|
||||
}
|
||||
invalid_sum
|
||||
}
|
||||
|
||||
#[aoc(day2, part2, Brute)]
|
||||
fn part2(input: &[RangeInclusive<u64>]) -> u64 {
|
||||
let mut invalid_sum = 0;
|
||||
for r in input {
|
||||
for product in r.clone() {
|
||||
let prod_s = product.to_string();
|
||||
for n in 1..=prod_s.len() / 2 {
|
||||
if !prod_s.len().is_multiple_of(n) {
|
||||
continue;
|
||||
}
|
||||
if prod_s
|
||||
.chars()
|
||||
.chunks(n)
|
||||
.into_iter()
|
||||
.map(|c| c.collect::<String>())
|
||||
.all_equal()
|
||||
{
|
||||
invalid_sum += product;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
invalid_sum
|
||||
}
|
||||
|
||||
#[aoc(day2, part1, ArithmeticBrute)]
|
||||
fn part1_arithmetic_brute(input: &[RangeInclusive<u64>]) -> u64 {
|
||||
let mut invalid_sum = 0;
|
||||
for r in input {
|
||||
// println!("Range: {:?}", r);
|
||||
for product in r.clone() {
|
||||
let n_digits = (product.ilog10() + 1) as usize;
|
||||
if !n_digits.is_multiple_of(2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let decade = POW10[n_digits / 2];
|
||||
let lhs = product / decade;
|
||||
let rhs = product % decade;
|
||||
// println!("{product} {n_digits}: D:{decade} L:{lhs} R:{rhs}");
|
||||
if lhs == rhs {
|
||||
invalid_sum += product
|
||||
}
|
||||
}
|
||||
}
|
||||
invalid_sum
|
||||
}
|
||||
|
||||
#[aoc(day2, part2, ArithmeticBrute)]
|
||||
fn part2_arithmetic_brute(input: &[RangeInclusive<u64>]) -> u64 {
|
||||
let mut invalid_sum = 0;
|
||||
for r in input {
|
||||
for product in r.clone() {
|
||||
let n_digits = (product.ilog10() + 1) as usize;
|
||||
|
||||
for n in 1..=n_digits / 2 {
|
||||
if !n_digits.is_multiple_of(n) {
|
||||
continue;
|
||||
}
|
||||
let repetitions = n_digits / n;
|
||||
let decade = POW10[n_digits - n]; // get the power of 10 to split the leftmost n digits
|
||||
let lhs = product / decade;
|
||||
let remainder = product % decade;
|
||||
|
||||
// for each repetition we multiply by 10^(rep * n) to add the appropriate zeros
|
||||
let expected_remainder = (0..repetitions - 1).map(|rep| lhs * POW10[rep * n]).sum();
|
||||
|
||||
if remainder == expected_remainder {
|
||||
invalid_sum += product;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
invalid_sum
|
||||
}
|
||||
|
||||
#[aoc(day2, part1, Clever)]
|
||||
fn part1_clever(input: &[RangeInclusive<u64>]) -> u64 {
|
||||
let mut invalid_sum = 0;
|
||||
for r in input {
|
||||
let n_digits = (r.start().ilog10() + 1) as usize;
|
||||
|
||||
let mut lhs = if !n_digits.is_multiple_of(2) {
|
||||
// If the number of digits is odd, we start our guess at the first possibility in the next decade
|
||||
POW10[n_digits / 2]
|
||||
} else {
|
||||
let start_decade = POW10[n_digits / 2];
|
||||
r.start() / start_decade
|
||||
};
|
||||
|
||||
// we will guess the next repeater, and check if it's in range, if not we are done.
|
||||
loop {
|
||||
let repeater = lhs * POW10[(lhs.ilog10() + 1) as usize] + lhs;
|
||||
if repeater < *r.start() {
|
||||
lhs += 1
|
||||
} else if r.contains(&repeater) {
|
||||
invalid_sum += repeater;
|
||||
lhs += 1
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
invalid_sum
|
||||
}
|
||||
|
||||
const fn n_digits(n: &u64) -> usize {
|
||||
(n.ilog10() + 1) as usize
|
||||
}
|
||||
|
||||
fn generate_repeaters(r: &RangeInclusive<u64>, n: usize) -> Vec<u64> {
|
||||
let mut invalids = Vec::new();
|
||||
for r in split_by_decade(r) {
|
||||
let n_digits = n_digits(r.start());
|
||||
if !n_digits.is_multiple_of(n) || n_digits < 2 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let repetitions = n_digits / n;
|
||||
let decade = POW10[n_digits - n];
|
||||
for lhs in (r.start() / decade)..=(r.end() / decade) {
|
||||
let repeater = (0..repetitions)
|
||||
.map(|rep| lhs * POW10[rep * n])
|
||||
.sum::<u64>();
|
||||
if r.contains(&repeater) {
|
||||
invalids.push(repeater)
|
||||
}
|
||||
}
|
||||
}
|
||||
invalids
|
||||
}
|
||||
|
||||
fn split_by_decade(r: &RangeInclusive<u64>) -> impl Iterator<Item = RangeInclusive<u64>> {
|
||||
let (start, end) = (*r.start(), *r.end());
|
||||
(n_digits(r.start())..n_digits(r.end()) + 1)
|
||||
.map(move |nd| RangeInclusive::new(max(start, POW10[nd - 1]), min(end, POW10[nd] - 1)))
|
||||
}
|
||||
|
||||
#[aoc(day2, part2, Clever)]
|
||||
fn part2_clever(input: &[RangeInclusive<u64>]) -> u64 {
|
||||
input
|
||||
.iter()
|
||||
.flat_map(|r| (1..=n_digits(r.end()) / 2).map(|nd| generate_repeaters(r, nd)))
|
||||
.flatten()
|
||||
.unique()
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "11-22,95-115,998-1012,1188511880-1188511890,222220-222224,1698522-1698528,446443-446449,38593856-38593862,565653-565659,824824821-824824827,2121212118-2121212124";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 1227775554);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 4174379265);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_arithmetic_example() {
|
||||
assert_eq!(part1_arithmetic_brute(&parse(EXAMPLE)), 1227775554);
|
||||
}
|
||||
#[test]
|
||||
fn part2_arithmetic_example() {
|
||||
assert_eq!(part2_arithmetic_brute(&parse(EXAMPLE)), 4174379265);
|
||||
}
|
||||
#[test]
|
||||
fn part1_clever_example() {
|
||||
assert_eq!(part1_clever(&parse(EXAMPLE)), 1227775554);
|
||||
}
|
||||
#[test]
|
||||
fn part2_clever_example() {
|
||||
assert_eq!(part2_clever(&parse(EXAMPLE)), 4174379265);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use cached::proc_macro::cached;
|
||||
use misc::POW10;
|
||||
|
||||
#[aoc_generator(day3)]
|
||||
fn parse(input: &str) -> Vec<Vec<u8>> {
|
||||
input
|
||||
.lines()
|
||||
.map(|bank| bank.bytes().map(|c| c - b'0').collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cached]
|
||||
fn max_joltage(bank: Vec<u8>, n: usize) -> u64 {
|
||||
if n == 1 {
|
||||
return *bank.iter().max().unwrap() as u64;
|
||||
}
|
||||
|
||||
(0..bank.len() - n + 1)
|
||||
.map(|start| {
|
||||
bank[start] as u64 * POW10[n - 1] + max_joltage(bank[start + 1..].to_vec(), n - 1)
|
||||
})
|
||||
.max()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn max_joltage_2(bank: &[u8], n: usize) -> u64 {
|
||||
if n == 1 {
|
||||
return *bank.iter().max().unwrap() as u64;
|
||||
}
|
||||
let choices = &bank[..bank.len() - (n - 1)];
|
||||
|
||||
// Note: can't use position_max() here since it returns the _last_ instance and we need the _first_.
|
||||
// get the max, then find the first instance of that value. There is definitely a one-pass solution.
|
||||
let max = choices.iter().max().unwrap();
|
||||
let choice = choices.iter().position(|n| max == n).unwrap();
|
||||
let rest = &bank[choice + 1..];
|
||||
|
||||
bank[choice] as u64 * POW10[n - 1] + max_joltage_2(rest, n - 1)
|
||||
}
|
||||
|
||||
#[aoc(day3, part1, Brute)]
|
||||
fn part1(input: &[Vec<u8>]) -> u64 {
|
||||
input.iter().map(|bank| max_joltage(bank.clone(), 2)).sum()
|
||||
}
|
||||
|
||||
#[aoc(day3, part2, Brute)]
|
||||
fn part2(input: &[Vec<u8>]) -> u64 {
|
||||
input.iter().map(|bank| max_joltage(bank.clone(), 12)).sum()
|
||||
}
|
||||
|
||||
#[aoc(day3, part1, Smart)]
|
||||
fn part1_smart(input: &[Vec<u8>]) -> u64 {
|
||||
input.iter().map(|bank| max_joltage_2(bank, 2)).sum()
|
||||
}
|
||||
|
||||
#[aoc(day3, part2, Smart)]
|
||||
fn part2_smart(input: &[Vec<u8>]) -> u64 {
|
||||
input.iter().map(|bank| max_joltage_2(bank, 12)).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "987654321111111
|
||||
811111111111119
|
||||
234234234234278
|
||||
818181911112111";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 357);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 3121910778619);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_smart_example() {
|
||||
assert_eq!(part1_smart(&parse(EXAMPLE)), 357);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_smart_example() {
|
||||
assert_eq!(part2_smart(&parse(EXAMPLE)), 3121910778619);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use grid::Grid;
|
||||
use itertools::Itertools;
|
||||
|
||||
#[aoc_generator(day4)]
|
||||
fn parse(input: &str) -> Grid<u8> {
|
||||
input.parse().unwrap()
|
||||
}
|
||||
|
||||
#[aoc(day4, part1, Brute)]
|
||||
fn part1(input: &Grid<u8>) -> u64 {
|
||||
(0..input.height() * input.width())
|
||||
.filter(|i| *input.get(&input.coord(*i as i64).unwrap()).unwrap() == b'@')
|
||||
.map(|i| input.adjacent_count(&input.coord(i as i64).unwrap(), |c| *c == b'@'))
|
||||
.filter(|n| *n < 4)
|
||||
.count() as u64
|
||||
}
|
||||
|
||||
#[aoc(day4, part2, Brute)]
|
||||
fn part2(input: &Grid<u8>) -> u64 {
|
||||
let mut grid = input.clone();
|
||||
let mut removed = 0;
|
||||
|
||||
loop {
|
||||
let mut removed_iteration = 0;
|
||||
for i in 0..grid.width() * grid.height() {
|
||||
let pos = grid.coord(i as i64).unwrap();
|
||||
if grid.get(&pos).is_some_and(|c| *c == b'@')
|
||||
&& grid.adjacent_count(&pos, |c| *c == b'@') < 4
|
||||
{
|
||||
// remove the roll
|
||||
grid.set(&pos, b'.');
|
||||
removed_iteration += 1;
|
||||
}
|
||||
}
|
||||
if removed_iteration == 0 {
|
||||
return removed;
|
||||
}
|
||||
removed += removed_iteration
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc(day4, part2, RollList)]
|
||||
fn part2_list(input: &Grid<u8>) -> u64 {
|
||||
let mut grid = input.clone();
|
||||
let mut to_check = grid.find_all(&b'@').collect_vec();
|
||||
let mut removed = 0;
|
||||
|
||||
while let Some(roll) = to_check.pop() {
|
||||
if grid.get(&roll).is_none_or(|c| *c == b'.') {
|
||||
continue;
|
||||
}
|
||||
let adjacent_rolls = grid
|
||||
.adjacent_iter(&roll)
|
||||
.filter_map(|i| if *i.value == b'@' { Some(i.pos) } else { None })
|
||||
.collect_vec();
|
||||
if adjacent_rolls.len() < 4 {
|
||||
grid.set(&roll, b'.');
|
||||
removed += 1;
|
||||
to_check.extend_from_slice(&adjacent_rolls);
|
||||
}
|
||||
}
|
||||
|
||||
removed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "..@@.@@@@.
|
||||
@@@.@.@.@@
|
||||
@@@@@.@.@@
|
||||
@.@@@@..@.
|
||||
@@.@@@@.@@
|
||||
.@@@@@@@.@
|
||||
.@.@.@.@@@
|
||||
@.@@@.@@@@
|
||||
.@@@@@@@@.
|
||||
@.@.@@@.@.";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 43);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_list_example() {
|
||||
assert_eq!(part2_list(&parse(EXAMPLE)), 43);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
use std::cmp::max;
|
||||
use std::fmt::Debug;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
|
||||
struct Database {
|
||||
fresh_ingredients: Vec<RangeInclusive<u64>>,
|
||||
available_ingredients: Vec<u64>,
|
||||
}
|
||||
|
||||
struct Database2 {
|
||||
fresh_ingredients: Vec<Span>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct Span {
|
||||
start: u64,
|
||||
end: u64,
|
||||
}
|
||||
|
||||
impl From<(u64, u64)> for Span {
|
||||
fn from(value: (u64, u64)) -> Self {
|
||||
Self {
|
||||
start: value.0,
|
||||
end: value.1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Span {
|
||||
fn len(&self) -> u64 {
|
||||
self.end - self.start + 1
|
||||
}
|
||||
}
|
||||
|
||||
struct RangeSet {
|
||||
ranges: Vec<Span>,
|
||||
}
|
||||
|
||||
impl RangeSet {
|
||||
fn new() -> Self {
|
||||
Self { ranges: Vec::new() }
|
||||
}
|
||||
fn simplify(&mut self) {
|
||||
if self.ranges.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mut modified = true;
|
||||
while modified {
|
||||
modified = false;
|
||||
// sort the ranges by start
|
||||
self.ranges.sort_by_key(|s| s.start);
|
||||
let mut new_ranges = Vec::new();
|
||||
let mut pos = 1;
|
||||
|
||||
while pos <= self.ranges.len() {
|
||||
// part of a disgusting hack to avoid skipping or double adding at the end
|
||||
if pos == self.ranges.len() {
|
||||
pos -= 1;
|
||||
}
|
||||
let (l, r) = (&self.ranges[pos - 1], &self.ranges[pos]);
|
||||
|
||||
if r.start <= l.end + 1 {
|
||||
modified = true;
|
||||
new_ranges.push((l.start, max(l.end, r.end)).into());
|
||||
// if we merged, skip checking the next range to avoid double-adding it
|
||||
// this screws us up at the very end, so need the disgusting hack above
|
||||
pos += 2;
|
||||
} else if pos < self.ranges.len() - 1 {
|
||||
// keep only the lhs if we didn't merge
|
||||
new_ranges.push(l.clone());
|
||||
pos += 1;
|
||||
} else {
|
||||
// at the end, keep both sides, otherwise the rhs gets excluded (if it didn't merge)
|
||||
new_ranges.push(l.clone());
|
||||
new_ranges.push(r.clone());
|
||||
pos += 2;
|
||||
}
|
||||
}
|
||||
|
||||
self.ranges = new_ranges;
|
||||
}
|
||||
}
|
||||
fn add(&mut self, s: Span) {
|
||||
self.ranges.push(s);
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day5)]
|
||||
fn parse(input: &str) -> Database {
|
||||
let mut fresh_ingredients = Vec::new();
|
||||
let mut available_ingredients = Vec::new();
|
||||
let mut parsing_ranges = true;
|
||||
for line in input.lines() {
|
||||
if line.is_empty() {
|
||||
parsing_ranges = false;
|
||||
continue;
|
||||
}
|
||||
if parsing_ranges {
|
||||
let (start, end) = line.split_once('-').unwrap();
|
||||
fresh_ingredients.push(RangeInclusive::new(
|
||||
start.parse().unwrap(),
|
||||
end.parse().unwrap(),
|
||||
));
|
||||
} else {
|
||||
available_ingredients.push(line.parse().unwrap())
|
||||
}
|
||||
}
|
||||
Database {
|
||||
fresh_ingredients,
|
||||
available_ingredients,
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc(day5, part1)]
|
||||
fn part1(input: &Database) -> u64 {
|
||||
input
|
||||
.available_ingredients
|
||||
.iter()
|
||||
.filter(|i| input.fresh_ingredients.iter().any(|r| r.contains(i)))
|
||||
.count() as u64
|
||||
}
|
||||
|
||||
#[aoc_generator(day5, part2, Naive)]
|
||||
fn parse2(input: &str) -> Database2 {
|
||||
let mut fresh_ingredients = Vec::new();
|
||||
for line in input.lines() {
|
||||
if line.is_empty() {
|
||||
return Database2 { fresh_ingredients };
|
||||
}
|
||||
let (start, end) = line.split_once('-').unwrap();
|
||||
fresh_ingredients.push((start.parse().unwrap(), end.parse().unwrap()).into());
|
||||
}
|
||||
Database2 { fresh_ingredients }
|
||||
}
|
||||
|
||||
#[aoc(day5, part2, Naive)]
|
||||
fn part2(input: &Database2) -> u64 {
|
||||
let mut all_ingredients = RangeSet::new();
|
||||
for r in &input.fresh_ingredients {
|
||||
all_ingredients.add(r.clone());
|
||||
}
|
||||
all_ingredients.simplify();
|
||||
all_ingredients.ranges.iter().map(|r| r.len()).sum::<u64>()
|
||||
}
|
||||
|
||||
#[aoc(day5, part2, RangeSet)]
|
||||
fn part2_rangeset(input: &Database) -> u64 {
|
||||
let mut all_ingredients = misc::range::RangeSet::new();
|
||||
for r in &input.fresh_ingredients {
|
||||
all_ingredients.add(r);
|
||||
}
|
||||
all_ingredients.store.iter().map(|r| r.end - r.start).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "3-5
|
||||
10-14
|
||||
16-20
|
||||
12-18
|
||||
|
||||
1
|
||||
5
|
||||
8
|
||||
11
|
||||
17
|
||||
32";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse2(EXAMPLE)), 14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_set_example() {
|
||||
assert_eq!(part2_rangeset(&parse(EXAMPLE)), 14);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use grid::Grid;
|
||||
use itertools::Itertools;
|
||||
use misc::POW10;
|
||||
use std::{
|
||||
fmt::{Display, Write},
|
||||
iter::repeat_n,
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
#[repr(u8)]
|
||||
enum Op {
|
||||
Add = b'+',
|
||||
Mul = b'*',
|
||||
}
|
||||
|
||||
impl From<&str> for Op {
|
||||
fn from(value: &str) -> Self {
|
||||
match value {
|
||||
"+" => Op::Add,
|
||||
"*" => Op::Mul,
|
||||
c => panic!("Invalid op `{c}`"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&u8> for Op {
|
||||
fn from(value: &u8) -> Self {
|
||||
match value {
|
||||
b'+' => Op::Add,
|
||||
b'*' => Op::Mul,
|
||||
c => panic!("Invalid op `{c}`"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Op {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Op::Add => f.write_char('+'),
|
||||
Op::Mul => f.write_char('*'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Op {
|
||||
fn f(&self, lhs: &u64, rhs: &u64) -> u64 {
|
||||
match self {
|
||||
Op::Add => lhs + rhs,
|
||||
Op::Mul => lhs * rhs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day6, part1)]
|
||||
fn parse(input: &str) -> (Grid<u64>, Vec<Op>) {
|
||||
let mut rows = input
|
||||
.lines()
|
||||
.map(|l| l.split_ascii_whitespace().collect_vec())
|
||||
.collect_vec();
|
||||
|
||||
let ops = rows
|
||||
.pop()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|op| Op::from(*op))
|
||||
.collect_vec();
|
||||
let mut grid = Grid::with_shape(rows[0].len(), rows.len(), 0);
|
||||
|
||||
for (y, r) in rows.iter().enumerate() {
|
||||
for (x, v) in r.iter().enumerate() {
|
||||
grid.set(&(x, y), v.parse().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
(grid, ops)
|
||||
}
|
||||
|
||||
#[aoc(day6, part1)]
|
||||
fn part1((grid, ops): &(Grid<u64>, Vec<Op>)) -> u64 {
|
||||
(0..grid.width())
|
||||
.map(|x| {
|
||||
grid.col_iter(x as i64)
|
||||
.unwrap()
|
||||
.cloned()
|
||||
.reduce(|l, r| ops[x].f(&l, &r))
|
||||
.unwrap()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
// fn split_digits(x: &u64) -> Vec<u8> {
|
||||
// let n_digits = x.ilog10() as usize;
|
||||
// (0..=n_digits)
|
||||
// .rev()
|
||||
// .map(|n| ((x / POW10[n]) % 10) as u8)
|
||||
// .collect()
|
||||
// }
|
||||
|
||||
#[aoc_generator(day6, part2, Spaghett)]
|
||||
fn parse2(input: &str) -> (Grid<Vec<char>>, Vec<Op>) {
|
||||
let mut rows = input.lines().collect_vec();
|
||||
let ops = rows.pop().unwrap();
|
||||
|
||||
let col_starts = ops
|
||||
.chars()
|
||||
.enumerate()
|
||||
.filter(|(_i, c)| *c == '+' || *c == '*')
|
||||
.map(|(i, _c)| i)
|
||||
.collect_vec();
|
||||
|
||||
let col_lengths = col_starts
|
||||
.iter()
|
||||
.tuple_windows()
|
||||
.map(|(l, r)| r - l - 1)
|
||||
.collect_vec();
|
||||
|
||||
let split_rows = rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
col_starts
|
||||
.iter()
|
||||
.zip(col_lengths.iter())
|
||||
.map(|(s, l)| &r[*s..s + l])
|
||||
.chain(repeat_n(&r[*col_starts.last().unwrap()..], 1))
|
||||
.collect_vec()
|
||||
})
|
||||
.collect_vec();
|
||||
|
||||
let ops = ops.split_ascii_whitespace().map(Op::from).collect_vec();
|
||||
let mut grid = Grid::with_shape(split_rows[0].len(), split_rows.len(), Vec::new());
|
||||
for (y, r) in split_rows.iter().enumerate() {
|
||||
for (x, v) in r.iter().enumerate() {
|
||||
grid.set(&(x, y), v.chars().collect_vec());
|
||||
}
|
||||
}
|
||||
|
||||
(grid, ops)
|
||||
}
|
||||
|
||||
#[aoc(day6, part2, Spaghett)]
|
||||
fn part2((grid, ops): &(Grid<Vec<char>>, Vec<Op>)) -> u64 {
|
||||
let mut columns = Vec::new();
|
||||
for col in 0..grid.width() {
|
||||
let mut digit = 0;
|
||||
let mut col_values = Vec::new();
|
||||
loop {
|
||||
let val = grid
|
||||
.col_iter(col as i64)
|
||||
.unwrap()
|
||||
.filter_map(|s| s.get(digit))
|
||||
.filter(|c| !c.is_ascii_whitespace())
|
||||
.map(|v| v.to_digit(10).unwrap() as u64)
|
||||
.fold(0, |acc, n| acc * 10 + n);
|
||||
if val == 0 {
|
||||
columns.push(col_values);
|
||||
break;
|
||||
}
|
||||
col_values.push(val);
|
||||
digit += 1;
|
||||
}
|
||||
}
|
||||
columns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(col, v)| v.iter().cloned().reduce(|l, r| ops[col].f(&l, &r)).unwrap())
|
||||
.sum::<u64>()
|
||||
}
|
||||
|
||||
#[aoc_generator(day6, part2, StateMachine)]
|
||||
fn parse2_walk(input: &str) -> Grid<u8> {
|
||||
Grid::from_str(input).unwrap()
|
||||
}
|
||||
|
||||
enum NextPos {
|
||||
Advance((usize, usize)),
|
||||
NewCol((usize, usize)),
|
||||
Done,
|
||||
}
|
||||
|
||||
#[aoc(day6, part2, StateMachine)]
|
||||
fn part2_walk(g: &Grid<u8>) -> u64 {
|
||||
let mut accum = 0;
|
||||
|
||||
// start at the bottom right
|
||||
let mut pos = (g.width() - 1, g.height() - 1);
|
||||
let mut digits = 0;
|
||||
let mut cur_value = 0;
|
||||
let mut cur_values = Vec::new();
|
||||
let mut cur_op = Op::Add;
|
||||
let mut last_col = false;
|
||||
|
||||
let height = g.height() - 1;
|
||||
|
||||
let next_pos = |(x, y)| -> NextPos {
|
||||
if y == 0 {
|
||||
if x == 0 {
|
||||
return NextPos::Done;
|
||||
}
|
||||
return NextPos::NewCol((x - 1, height));
|
||||
}
|
||||
NextPos::Advance((x, y - 1))
|
||||
};
|
||||
|
||||
while let Some(cur_char) = g.get(&pos) {
|
||||
match cur_char {
|
||||
b'*' | b'+' => {
|
||||
last_col = true;
|
||||
cur_op = cur_char.into()
|
||||
}
|
||||
cur_char if cur_char.is_ascii_digit() => {
|
||||
cur_value += (*cur_char - b'0') as u64 * POW10[digits];
|
||||
digits += 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pos = match next_pos(pos) {
|
||||
NextPos::Advance(p) => p,
|
||||
NextPos::NewCol(p) => {
|
||||
// add the value
|
||||
if cur_value != 0 {
|
||||
cur_values.push(cur_value);
|
||||
cur_value = 0;
|
||||
}
|
||||
digits = 0;
|
||||
// this was a last col, so reduce and accumulate
|
||||
if last_col {
|
||||
accum += cur_values
|
||||
.iter()
|
||||
.cloned()
|
||||
.reduce(|l, r| cur_op.f(&l, &r))
|
||||
.unwrap_or(0);
|
||||
// clear the state
|
||||
cur_values.clear();
|
||||
last_col = false;
|
||||
}
|
||||
p
|
||||
}
|
||||
NextPos::Done => {
|
||||
if cur_value != 0 {
|
||||
cur_values.push(cur_value);
|
||||
}
|
||||
// accumulate the final result
|
||||
accum += cur_values
|
||||
.iter()
|
||||
.cloned()
|
||||
.reduce(|l, r| cur_op.f(&l, &r))
|
||||
.unwrap_or(0);
|
||||
return accum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = r"123 328 51 64
|
||||
45 64 387 23
|
||||
6 98 215 314
|
||||
* + * + ";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 4277556);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse2(EXAMPLE)), 3263827);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_walk_example() {
|
||||
assert_eq!(part2_walk(&parse2_walk(EXAMPLE)), 3263827);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use grid::{Coord2d, Grid};
|
||||
use std::str::FromStr;
|
||||
|
||||
#[aoc_generator(day7)]
|
||||
fn parse(input: &str) -> Grid<u8> {
|
||||
Grid::from_str(input).unwrap()
|
||||
}
|
||||
|
||||
fn emit_beams(grid: &mut Grid<u8>, pos: Coord2d) -> u64 {
|
||||
match grid.set(&pos, b'|') {
|
||||
None | Some(b'|') => 0,
|
||||
Some(b'.') | Some(b'S') => emit_beams(grid, pos + &(0, 1)),
|
||||
Some(b'^') => 1 + emit_beams(grid, pos + &(-1, 0)) + emit_beams(grid, pos + &(1, 0)),
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc(day7, part1)]
|
||||
fn part1(input: &Grid<u8>) -> u64 {
|
||||
let mut grid = input.clone();
|
||||
emit_beams(&mut grid, input.find(&b'S').unwrap())
|
||||
}
|
||||
|
||||
#[aoc(day7, part2)]
|
||||
fn part2(input: &Grid<u8>) -> u64 {
|
||||
let mut col_counts = vec![0; input.width()];
|
||||
col_counts[input.find(&b'S').unwrap().x as usize] = 1;
|
||||
|
||||
// Start row is already set up
|
||||
for y in 1..input.height() {
|
||||
// for each column with non-zero counts
|
||||
for x in 0..input.width() {
|
||||
if col_counts[x] == 0 {
|
||||
continue;
|
||||
}
|
||||
match input.get(&(x, y)) {
|
||||
// if our current position is a caret, add that count to our neighbours
|
||||
Some(b'^') => {
|
||||
for col in [x as i64 - 1, x as i64 + 1]
|
||||
.into_iter()
|
||||
.filter(|x| *x >= 0 && *x < input.width() as i64)
|
||||
{
|
||||
col_counts[col as usize] += col_counts[x];
|
||||
}
|
||||
col_counts[x] = 0;
|
||||
}
|
||||
// if our current position is a . do nothing, it's already counted
|
||||
Some(b'.') => continue,
|
||||
Some(c) => panic!("unexpected character {c}"),
|
||||
None => panic!("How did we end up outside the grid?"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
col_counts.iter().sum::<u64>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TRIVIAL_EXAMPLE: &str = "...S...
|
||||
.......
|
||||
...^...
|
||||
..^.^.^
|
||||
...^.^.
|
||||
.......
|
||||
.......";
|
||||
|
||||
const EXAMPLE: &str = ".......S.......
|
||||
...............
|
||||
.......^.......
|
||||
...............
|
||||
......^.^......
|
||||
...............
|
||||
.....^.^.^.....
|
||||
...............
|
||||
....^.^...^....
|
||||
...............
|
||||
...^.^...^.^...
|
||||
...............
|
||||
..^...^.....^..
|
||||
...............
|
||||
.^.^.^.^.^...^.
|
||||
...............";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 21);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_trivial_example() {
|
||||
assert_eq!(part2(&parse(TRIVIAL_EXAMPLE)), 7);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
use std::{cmp::Reverse, collections::BinaryHeap, fmt::Display};
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use itertools::Itertools;
|
||||
|
||||
#[derive(PartialEq, Clone, Debug)]
|
||||
struct Junction {
|
||||
pos: (i64, i64, i64),
|
||||
}
|
||||
|
||||
fn squared_distance(a: &Junction, b: &Junction) -> u64 {
|
||||
// if a.pos == b.pos {
|
||||
// 0
|
||||
// } else {
|
||||
(a.pos.0 - b.pos.0).pow(2) as u64
|
||||
+ (a.pos.1 - b.pos.1).pow(2) as u64
|
||||
+ (a.pos.2 - b.pos.2).pow(2) as u64
|
||||
// }
|
||||
}
|
||||
|
||||
impl Junction {
|
||||
fn squared_distance(&self, other: &Junction) -> u64 {
|
||||
squared_distance(self, other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Junction {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"({},{},{})",
|
||||
self.pos.0, self.pos.1, self.pos.2
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Junction {
|
||||
fn from(value: &str) -> Self {
|
||||
Self {
|
||||
pos: value
|
||||
.split(',')
|
||||
.map(|v| v.parse().unwrap())
|
||||
.collect_tuple()
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Circuits {
|
||||
junctions: Vec<Junction>,
|
||||
circuits: Vec<Vec<usize>>,
|
||||
}
|
||||
|
||||
impl Circuits {
|
||||
fn find_circuit(&self, junction: usize) -> usize {
|
||||
self.circuits
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_i, c)| c.contains(&junction))
|
||||
.map(|(i, _c)| i)
|
||||
.unwrap()
|
||||
}
|
||||
fn merge_circuits(&mut self, a: usize, b: usize) {
|
||||
if a == b {
|
||||
return;
|
||||
}
|
||||
let mut items = std::mem::take(&mut self.circuits[b]);
|
||||
self.circuits[a].append(&mut items);
|
||||
self.circuits.remove(b);
|
||||
}
|
||||
|
||||
fn connect(&mut self, a: usize, b: usize) {
|
||||
let a_circuit = self.find_circuit(a);
|
||||
let b_circuit = self.find_circuit(b);
|
||||
|
||||
self.merge_circuits(a_circuit, b_circuit); // both are already in circuits, merge them
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day8)]
|
||||
fn parse(input: &str) -> Circuits {
|
||||
let junctions = input.lines().map(|l| l.into()).collect_vec();
|
||||
|
||||
Circuits {
|
||||
circuits: Vec::from_iter((0..junctions.len()).map(|i| vec![i])),
|
||||
junctions,
|
||||
}
|
||||
}
|
||||
|
||||
fn part1_impl(input: &Circuits, n: usize) -> u64 {
|
||||
let mut circuits = input.clone();
|
||||
for (a, b, _d) in circuits
|
||||
.junctions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.tuple_combinations()
|
||||
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.squared_distance(b)))
|
||||
.sorted_unstable_by_key(|(_a_pos, _b_pos, d)| *d)
|
||||
.take(n)
|
||||
{
|
||||
circuits.connect(a, b)
|
||||
}
|
||||
|
||||
circuits
|
||||
.circuits
|
||||
.iter()
|
||||
.map(|c| c.len())
|
||||
.sorted_unstable()
|
||||
.rev()
|
||||
.take(3)
|
||||
.reduce(|a, b| a * b)
|
||||
.unwrap() as u64
|
||||
}
|
||||
|
||||
#[aoc(day8, part1, Sorted)]
|
||||
fn part1(input: &Circuits) -> u64 {
|
||||
part1_impl(input, 1000)
|
||||
}
|
||||
|
||||
#[aoc(day8, part2, Sorted)]
|
||||
fn part2(input: &Circuits) -> u64 {
|
||||
let mut circuits = input.clone();
|
||||
|
||||
for (a, b, _d) in circuits
|
||||
.junctions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.tuple_combinations()
|
||||
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.squared_distance(b)))
|
||||
.sorted_unstable_by_key(|(_a_pos, _b_pos, d)| *d)
|
||||
{
|
||||
circuits.connect(a, b);
|
||||
if circuits.circuits.len() == 1 {
|
||||
return (circuits.junctions[a].pos.0 * circuits.junctions[b].pos.0) as u64;
|
||||
}
|
||||
}
|
||||
|
||||
panic!()
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct JunctionPair {
|
||||
d: u64,
|
||||
a: usize,
|
||||
b: usize,
|
||||
}
|
||||
|
||||
fn make_heap(circuits: &Circuits) -> BinaryHeap<Reverse<JunctionPair>> {
|
||||
BinaryHeap::from_iter(
|
||||
circuits
|
||||
.junctions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.tuple_combinations()
|
||||
.map(|((a_pos, a), (b_pos, b))| {
|
||||
Reverse(JunctionPair {
|
||||
a: a_pos,
|
||||
b: b_pos,
|
||||
d: a.squared_distance(b),
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn part1_heaped_impl(input: &Circuits, n: usize) -> u64 {
|
||||
let mut circuits = input.clone();
|
||||
let mut distances = make_heap(&circuits);
|
||||
|
||||
for _ in 0..n {
|
||||
let pair = distances.pop().unwrap().0;
|
||||
circuits.connect(pair.a, pair.b);
|
||||
}
|
||||
|
||||
circuits
|
||||
.circuits
|
||||
.iter()
|
||||
.map(|c| c.len())
|
||||
.sorted_unstable()
|
||||
.rev()
|
||||
.take(3)
|
||||
.reduce(|a, b| a * b)
|
||||
.unwrap() as u64
|
||||
}
|
||||
|
||||
#[aoc(day8, part1, Heaped)]
|
||||
fn part1_heaped(input: &Circuits) -> u64 {
|
||||
part1_heaped_impl(input, 1000)
|
||||
}
|
||||
|
||||
#[aoc(day8, part2, Heaped)]
|
||||
fn part2_heaped(input: &Circuits) -> u64 {
|
||||
let mut circuits = input.clone();
|
||||
let mut distances = make_heap(&circuits);
|
||||
|
||||
while let Some(Reverse(jp)) = distances.pop() {
|
||||
circuits.connect(jp.a, jp.b);
|
||||
if circuits.circuits.len() == 1 {
|
||||
return (circuits.junctions[jp.a].pos.0 * circuits.junctions[jp.b].pos.0) as u64;
|
||||
}
|
||||
}
|
||||
|
||||
panic!()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "162,817,812
|
||||
57,618,57
|
||||
906,360,560
|
||||
592,479,940
|
||||
352,342,300
|
||||
466,668,158
|
||||
542,29,236
|
||||
431,825,988
|
||||
739,650,466
|
||||
52,470,668
|
||||
216,146,977
|
||||
819,987,18
|
||||
117,168,530
|
||||
805,96,715
|
||||
346,949,466
|
||||
970,615,88
|
||||
941,993,340
|
||||
862,61,35
|
||||
984,92,344
|
||||
425,690,689";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1_impl(&parse(EXAMPLE), 10), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_heaped_example() {
|
||||
assert_eq!(part1_heaped_impl(&parse(EXAMPLE), 10), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 25272);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_heaped_example() {
|
||||
assert_eq!(part2_heaped(&parse(EXAMPLE)), 25272);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use grid::{AsCoord2d, Coord2d, Grid};
|
||||
use indicatif::{ParallelProgressIterator, ProgressIterator, ProgressStyle};
|
||||
use itertools::Itertools;
|
||||
use rayon::prelude::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::{
|
||||
cmp::{max, min},
|
||||
fmt::Display,
|
||||
};
|
||||
|
||||
#[aoc_generator(day9)]
|
||||
fn parse(input: &str) -> Vec<Coord2d> {
|
||||
input
|
||||
.lines()
|
||||
.map(|l| l.parse::<Coord2d>().unwrap())
|
||||
.map(|c| Coord2d {
|
||||
x: c.x + 1, // allow a buffer zone
|
||||
y: c.y + 1,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[aoc(day9, part1)]
|
||||
fn part1(input: &Vec<Coord2d>) -> u64 {
|
||||
input
|
||||
.iter()
|
||||
.tuple_combinations()
|
||||
.inspect(|(a, b)| {
|
||||
println!(
|
||||
"{a} vs {b} = {}",
|
||||
a.x().abs_diff(b.x()) * a.y().abs_diff(b.y())
|
||||
)
|
||||
})
|
||||
.map(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1))
|
||||
.sorted_unstable()
|
||||
.next_back()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn build_grid(reds: &Vec<Coord2d>) -> Grid<u8> {
|
||||
let width = reds.iter().map(|c| c.x()).max().unwrap() + 3;
|
||||
let height = reds.iter().map(|c| c.y()).max().unwrap() + 3;
|
||||
|
||||
let mut grid = Grid::with_shape(width as usize, height as usize, b'.');
|
||||
let mut prev = reds.last().unwrap();
|
||||
for c in reds {
|
||||
// mark c filled
|
||||
grid.set(&c, b'#');
|
||||
// build a line of green between it and the previous
|
||||
if c.x() == prev.x() {
|
||||
// vertical
|
||||
for y in (min(c.y(), prev.y()) + 1)..max(c.y(), prev.y()) {
|
||||
grid.set(&(c.x(), y), b'X');
|
||||
}
|
||||
} else if c.y() == prev.y() {
|
||||
// horiztonal
|
||||
for x in (min(c.x(), prev.x()) + 1)..max(c.x(), prev.x()) {
|
||||
grid.set(&(x, c.y()), b'X');
|
||||
}
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
prev = c
|
||||
}
|
||||
|
||||
grid
|
||||
}
|
||||
|
||||
fn build_hashgrid(reds: &Vec<Coord2d>) -> HashMap<Coord2d, u8> {
|
||||
let mut grid = HashMap::new();
|
||||
let mut prev = reds.last().unwrap();
|
||||
for c in reds {
|
||||
// mark c filled
|
||||
grid.insert(*c, b'#');
|
||||
// build a line of green between it and the previous
|
||||
if c.x() == prev.x() {
|
||||
// vertical
|
||||
for y in (min(c.y(), prev.y()) + 1)..max(c.y(), prev.y()) {
|
||||
grid.insert(Coord2d { x: c.x(), y }, b'X');
|
||||
}
|
||||
} else if c.y() == prev.y() {
|
||||
// horiztonal
|
||||
for x in (min(c.x(), prev.x()) + 1)..max(c.x(), prev.x()) {
|
||||
grid.insert(Coord2d { x, y: c.y() }, b'X');
|
||||
}
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
prev = c
|
||||
}
|
||||
|
||||
grid
|
||||
}
|
||||
|
||||
fn flood_fill(grid: &mut Grid<u8>, pos: Coord2d) {
|
||||
if grid.get(&pos) != Some(&b'.') {
|
||||
return;
|
||||
}
|
||||
let mut q = VecDeque::new();
|
||||
q.push_back(pos);
|
||||
while let Some(next) = q.pop_front() {
|
||||
let (mut lx, mut rx) = (next.x, next.x);
|
||||
while grid.get(&Coord2d {
|
||||
x: lx - 1,
|
||||
y: next.y,
|
||||
}) == Some(&b'.')
|
||||
{
|
||||
grid.set(
|
||||
&Coord2d {
|
||||
x: lx - 1,
|
||||
y: next.y,
|
||||
},
|
||||
b'X',
|
||||
);
|
||||
lx -= 1;
|
||||
}
|
||||
while grid.get(&Coord2d { x: rx, y: next.y }) == Some(&b'.') {
|
||||
grid.set(&Coord2d { x: rx, y: next.y }, b'X');
|
||||
rx += 1;
|
||||
}
|
||||
flood_scan(grid, lx, rx, next.y + 1, &mut q);
|
||||
flood_scan(grid, lx, rx, next.y - 1, &mut q);
|
||||
}
|
||||
}
|
||||
|
||||
fn flood_scan(grid: &mut Grid<u8>, lx: i64, rx: i64, y: i64, q: &mut VecDeque<Coord2d>) {
|
||||
let mut span_added = false;
|
||||
for x in lx..rx {
|
||||
if grid.get(&Coord2d { x, y }) != Some(&b'.') {
|
||||
span_added = false
|
||||
} else if !span_added {
|
||||
q.push_back(Coord2d { x, y });
|
||||
span_added = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// #[aoc(day9, part2, Brute)]
|
||||
fn part2(reds: &Vec<Coord2d>) -> u64 {
|
||||
let mut grid = build_grid(reds);
|
||||
// Find the first red starting at top left - 'inside' must be to its bottom right
|
||||
let start = grid.find(&b'#').unwrap();
|
||||
flood_fill(&mut grid, start + &(1, 1).to_coord());
|
||||
// println!("{grid}");
|
||||
|
||||
let pairs = reds
|
||||
.iter()
|
||||
.tuple_combinations()
|
||||
.sorted_unstable_by_key(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1))
|
||||
.rev()
|
||||
.progress()
|
||||
.collect_vec();
|
||||
|
||||
let (a, b) = pairs
|
||||
.par_iter()
|
||||
.progress_with_style(
|
||||
ProgressStyle::with_template(
|
||||
"[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}",
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.filter(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1) < 2972065369) // FIXME: PROGRESS CAPTURE
|
||||
.map(|(a, b)| {
|
||||
for y in (min(a.y(), b.y()))..=max(a.y(), b.y()) {
|
||||
for x in (min(a.x(), b.x()))..=max(a.x(), b.y()) {
|
||||
if *grid.get(&(x, y)).unwrap() == b'.' {
|
||||
return (false, a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
(true, a, b)
|
||||
})
|
||||
.find_map_first(|(good, a, b)| if good { Some((a, b)) } else { None })
|
||||
.unwrap();
|
||||
// println!("win: {a} {b}");
|
||||
(a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1)
|
||||
}
|
||||
|
||||
fn line_square_intersection<LT: AsCoord2d, ST: AsCoord2d>(
|
||||
&(l1, l2): &(<, <),
|
||||
&(sq1, sq2): &(&ST, &ST),
|
||||
) -> bool
|
||||
where
|
||||
LT: Clone + Display,
|
||||
ST: Clone + Display,
|
||||
{
|
||||
let min_x = min(sq1.x(), sq2.x());
|
||||
let max_x = max(sq1.x(), sq2.x());
|
||||
let min_y = min(sq1.y(), sq2.y());
|
||||
let max_y = max(sq1.y(), sq2.y());
|
||||
|
||||
// println!("({},{}) X [{},{}]", l1, l2, sq1, sq2);
|
||||
// line is horizontal
|
||||
if l1.y() == l2.y() {
|
||||
// println!(" horizontal at y={}", l1.y());
|
||||
// above, below, or touching square
|
||||
if l1.y() <= min_y || l1.y() >= max_y {
|
||||
// println!(" y out of range or touching");
|
||||
false
|
||||
// start inside
|
||||
} else if min(l1.x(), l2.x()) >= min_x && min(l1.x(), l2.x()) <= max_x {
|
||||
// println!(" start inside");
|
||||
true
|
||||
//end inside
|
||||
} else if max(l1.x(), l2.x()) >= min_x && max(l1.x(), l2.x()) <= max_x {
|
||||
// println!(" end inside");
|
||||
true
|
||||
} else {
|
||||
// println!(" no overlap on x");
|
||||
false
|
||||
}
|
||||
// line is vertical
|
||||
} else {
|
||||
// println!(" vertical at x={}", l1.x());
|
||||
if l1.x() <= min_x || l1.x() >= max_x {
|
||||
// println!(" x out of range or touching");
|
||||
false
|
||||
// start inside
|
||||
} else if min(l1.y(), l2.y()) >= min_y && min(l1.y(), l2.y()) <= max_y {
|
||||
// println!(" start inside");
|
||||
true
|
||||
//end inside
|
||||
} else if max(l1.y(), l2.y()) >= min_y && max(l1.y(), l2.y()) <= max_y {
|
||||
// println!(" end inside");
|
||||
true
|
||||
} else {
|
||||
// println!(" no overlap on y");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait Rectangle {
|
||||
fn top_left(&self) -> Coord2d;
|
||||
fn bottom_right(&self) -> Coord2d;
|
||||
fn in_bounds<T: AsCoord2d>(&self, b: &T) -> bool {
|
||||
b.x() >= self.top_left().x
|
||||
&& b.x() <= self.bottom_right().x()
|
||||
&& b.y() >= self.top_left().y()
|
||||
&& b.y() <= self.bottom_right().y()
|
||||
}
|
||||
fn area(&self) -> u64 {
|
||||
let a = self.top_left();
|
||||
let b = self.bottom_right();
|
||||
(a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1)
|
||||
}
|
||||
}
|
||||
|
||||
impl Rectangle for (&Coord2d, &Coord2d) {
|
||||
fn top_left(&self) -> Coord2d {
|
||||
Coord2d {
|
||||
x: min(self.0.x, self.1.x),
|
||||
y: min(self.0.y, self.1.y),
|
||||
}
|
||||
}
|
||||
fn bottom_right(&self) -> Coord2d {
|
||||
Coord2d {
|
||||
x: max(self.0.x, self.1.x),
|
||||
y: max(self.0.y, self.1.y),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// true = clockwise
|
||||
fn outside_points(prev: &Coord2d, cur: &Coord2d, next: &Coord2d) -> Vec<Coord2d> {
|
||||
let l1_diff = ((cur.x - prev.x).signum(), (cur.y - prev.y).signum());
|
||||
let l2_diff = ((next.x - cur.x).signum(), (next.y - cur.y).signum());
|
||||
|
||||
match (l1_diff, l2_diff) {
|
||||
// CW
|
||||
((1, 0), (0, 1)) => vec![cur + (0, -1), cur + (1, -1), cur + (1, 0)], // x^ y^
|
||||
((0, 1), (-1, 0)) => vec![cur + (1, 0), cur + (1, 1), cur + (0, 1)],
|
||||
((-1, 0), (0, -1)) => vec![cur + (0, 1), cur + (-1, 1), cur + (-1, 0)], // xv yv
|
||||
((0, -1), (1, 0)) => vec![cur + (-1, 0), cur + (-1, -1), cur + (0, -1)], // yv x^
|
||||
// CCW
|
||||
((0, 1), (1, 0)) => vec![cur + (1, -1)],
|
||||
((1, 0), (0, -1)) => vec![cur + (-1, -1)],
|
||||
((0, -1), (-1, 0)) => vec![cur + (-1, 1)],
|
||||
((-1, 0), (0, 1)) => vec![cur + (1, 1)],
|
||||
((0, _), (0, _)) | ((_, 0), (_, 0)) => vec![], // colinear
|
||||
_ => panic!(
|
||||
"unexpected line arrangement {:?} {:?} @ [({},{}), ({},{}), ({},{})",
|
||||
l1_diff, l2_diff, prev.x, prev.y, cur.x, cur.y, next.x, next.y
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc(day9, part2, Lines)]
|
||||
fn part2_lines(reds: &Vec<Coord2d>) -> u64 {
|
||||
// let mut grid = build_hashgrid(reds);
|
||||
// let mut grid = build_grid(reds);
|
||||
// // println!("{grid}");
|
||||
// let area: i64 = reds
|
||||
// .iter()
|
||||
// .circular_tuple_windows()
|
||||
// .map(|(a, b)| (a.x * b.y) - (b.x * a.y))
|
||||
// .sum();
|
||||
// let outside_points: HashMap<&Coord2d, Vec<Coord2d>> = if area < 0 {
|
||||
// reds.iter()
|
||||
// .rev()
|
||||
// .circular_tuple_windows()
|
||||
// .map(|(a, b, c)| (b, outside_points(a, b, c)))
|
||||
// .collect()
|
||||
// } else {
|
||||
// reds.iter()
|
||||
// .circular_tuple_windows()
|
||||
// .map(|(a, b, c)| (b, outside_points(a, b, c)))
|
||||
// .collect()
|
||||
// };
|
||||
|
||||
// for corner in reds {
|
||||
// for p in &outside_points[corner] {
|
||||
// if *grid.get(p).unwrap() == b'.' {
|
||||
// grid.set(p, b'O');
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// println!("{grid}");
|
||||
|
||||
// still iterate over the possible rectangles in size order
|
||||
for rect in reds
|
||||
.iter()
|
||||
.tuple_combinations()
|
||||
.sorted_unstable_by_key(|rect: &(&Coord2d, &Coord2d)| rect.area())
|
||||
.rev()
|
||||
.progress_with_style(
|
||||
ProgressStyle::with_template(
|
||||
"[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}",
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
{
|
||||
let tl = rect.top_left();
|
||||
let br = rect.bottom_right();
|
||||
|
||||
let invalid = reds.iter().circular_tuple_windows().any(|(a, b)| {
|
||||
// 1. A polygon vertex lies strictly inside the rectangle
|
||||
let node_inside = tl.x < a.x && a.x < br.x && tl.y < a.y && a.y < br.y;
|
||||
|
||||
// 2. A polygon edge slices all the way across the rectangle
|
||||
let crosses_bounds = if a.x == b.x {
|
||||
let (ey_min, ey_max) = (a.y.min(b.y), a.y.max(b.y));
|
||||
(tl.x < a.x && a.x < br.x) && (ey_min <= tl.y && ey_max >= br.y)
|
||||
} else {
|
||||
let (ex_min, ex_max) = (a.x.min(b.x), a.x.max(b.x));
|
||||
(tl.y < a.y && a.y < br.y) && (ex_min <= tl.x && ex_max >= br.x)
|
||||
};
|
||||
|
||||
node_inside || crosses_bounds
|
||||
});
|
||||
|
||||
if invalid {
|
||||
continue;
|
||||
}
|
||||
|
||||
// println!(
|
||||
// "win! {},{} = {}",
|
||||
// rect.top_left(),
|
||||
// rect.bottom_right(),
|
||||
// rect.area()
|
||||
// );
|
||||
// grid.set(&rect.top_left(), b'*');
|
||||
// grid.set(&rect.bottom_right(), b'*');
|
||||
|
||||
// println!("{grid}");
|
||||
return rect.area();
|
||||
}
|
||||
panic!()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rstest::rstest;
|
||||
|
||||
const EXAMPLE: &str = "7,1
|
||||
11,1
|
||||
11,7
|
||||
9,7
|
||||
9,5
|
||||
2,5
|
||||
2,3
|
||||
7,3";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 24);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(
|
||||
"7,1
|
||||
11,1
|
||||
11,7
|
||||
9,7
|
||||
9,5
|
||||
2,5
|
||||
2,3
|
||||
7,3",
|
||||
24
|
||||
)]
|
||||
#[case(
|
||||
"4,2
|
||||
13,2
|
||||
13,4
|
||||
8,4
|
||||
8,6
|
||||
11,6
|
||||
11,10
|
||||
4,10",
|
||||
40
|
||||
)]
|
||||
#[case(
|
||||
"3,2
|
||||
17,2
|
||||
17,13
|
||||
13,13
|
||||
13,11
|
||||
15,11
|
||||
15,8
|
||||
11,8
|
||||
11,15
|
||||
18,15
|
||||
18,17
|
||||
4,17
|
||||
4,12
|
||||
6,12
|
||||
6,5
|
||||
3,5",
|
||||
66
|
||||
)]
|
||||
#[case(
|
||||
"2,2
|
||||
8,2
|
||||
8,6
|
||||
5,6
|
||||
5,4
|
||||
2,4",
|
||||
21
|
||||
)]
|
||||
#[case(
|
||||
"3,1
|
||||
12,1
|
||||
12,4
|
||||
9,4
|
||||
9,8
|
||||
3,8",
|
||||
56
|
||||
)]
|
||||
#[case(
|
||||
"7,1
|
||||
11,1
|
||||
11,3
|
||||
13,3
|
||||
13,5
|
||||
11,5
|
||||
11,7
|
||||
9,7
|
||||
9,5
|
||||
2,5
|
||||
2,3
|
||||
7,3",
|
||||
36
|
||||
)]
|
||||
#[case(
|
||||
"1,2
|
||||
8,2
|
||||
8,4
|
||||
6,4
|
||||
6,5
|
||||
9,5
|
||||
9,8
|
||||
1,8",
|
||||
56
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
4,1
|
||||
4,5
|
||||
7,5
|
||||
7,1
|
||||
10,1
|
||||
10,8
|
||||
1,8",
|
||||
32
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
5,1
|
||||
5,6
|
||||
7,6
|
||||
7,1
|
||||
11,1
|
||||
11,9
|
||||
1,9",
|
||||
45
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
5,1
|
||||
5,7
|
||||
6,7
|
||||
6,1
|
||||
10,1
|
||||
10,9
|
||||
1,9",
|
||||
90
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
12,1
|
||||
12,8
|
||||
10,8
|
||||
10,3
|
||||
8,3
|
||||
8,8
|
||||
6,8
|
||||
6,3
|
||||
4,3
|
||||
4,8
|
||||
1,8",
|
||||
32
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
1,8
|
||||
10,8
|
||||
10,1
|
||||
7,1
|
||||
7,5
|
||||
4,5
|
||||
4,1",
|
||||
32
|
||||
)]
|
||||
#[case(
|
||||
"4,1
|
||||
7,1
|
||||
7,4
|
||||
10,4
|
||||
10,7
|
||||
7,7
|
||||
7,10
|
||||
4,10
|
||||
4,7
|
||||
1,7
|
||||
1,4
|
||||
4,4",
|
||||
40
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
12,1
|
||||
12,10
|
||||
1,10
|
||||
1,8
|
||||
10,8
|
||||
10,3
|
||||
1,3",
|
||||
36
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
10,1
|
||||
10,6
|
||||
4,6
|
||||
4,8
|
||||
10,8
|
||||
10,12
|
||||
1,12
|
||||
1,7
|
||||
7,7
|
||||
7,4
|
||||
1,4",
|
||||
50
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
10,1
|
||||
10,10
|
||||
3,10
|
||||
3,4
|
||||
7,4
|
||||
7,7
|
||||
5,7
|
||||
5,6
|
||||
6,6
|
||||
6,5
|
||||
4,5
|
||||
4,9
|
||||
9,9
|
||||
9,2
|
||||
1,2",
|
||||
20
|
||||
)]
|
||||
#[case(
|
||||
"1,1
|
||||
5,1
|
||||
5,3
|
||||
7,3
|
||||
7,4
|
||||
2,4
|
||||
2,7
|
||||
7,7
|
||||
7,8
|
||||
3,8
|
||||
3,11
|
||||
1,11",
|
||||
16
|
||||
)]
|
||||
|
||||
fn part2_lines_example(#[case] input: &str, #[case] answer: u64) {
|
||||
assert_eq!(part2_lines(&parse(input)), answer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
mod day1;
|
||||
mod day10;
|
||||
mod day11;
|
||||
mod day12;
|
||||
mod day2;
|
||||
mod day3;
|
||||
mod day4;
|
||||
mod day5;
|
||||
mod day6;
|
||||
mod day7;
|
||||
mod day8;
|
||||
mod day9;
|
||||
|
||||
use aoc_runner_derive::aoc_lib;
|
||||
|
||||
aoc_lib! { year = 2025 }
|
||||
@@ -0,0 +1,3 @@
|
||||
use aoc_runner_derive::aoc_main;
|
||||
|
||||
aoc_main! { lib = aoc2025 }
|
||||
Reference in new issue
Block a user