day8: part1 solution

This commit is contained in:
2025-12-08 00:59:29 -08:00
parent e97931acf3
commit 41f9e971ee

View File

@@ -1,12 +1,6 @@
use std::{ use std::{f64, fmt::Display};
collections::{HashMap, HashSet},
f64,
fmt::{Display, Write},
iter::repeat_n,
};
use aoc_runner_derive::{aoc, aoc_generator}; use aoc_runner_derive::{aoc, aoc_generator};
use cached::proc_macro::cached;
use itertools::Itertools; use itertools::Itertools;
#[derive(Eq, PartialEq, Clone, Debug, Hash)] #[derive(Eq, PartialEq, Clone, Debug, Hash)]
@@ -55,7 +49,6 @@ impl From<&str> for Junction {
struct Circuits { struct Circuits {
junctions: Vec<Junction>, junctions: Vec<Junction>,
circuits: Vec<Vec<usize>>, circuits: Vec<Vec<usize>>,
checked: HashSet<(usize, usize)>,
} }
impl Circuits { impl Circuits {
@@ -79,7 +72,6 @@ impl Circuits {
fn connect(&mut self, a: usize, b: usize) { fn connect(&mut self, a: usize, b: usize) {
let a_circuit = self.find_circuit(a); let a_circuit = self.find_circuit(a);
let b_circuit = self.find_circuit(b); let b_circuit = self.find_circuit(b);
self.checked.insert((a, b));
match (a_circuit, b_circuit) { match (a_circuit, b_circuit) {
(None, None) => self.circuits.push(vec![a, b]), // both are unconnected (None, None) => self.circuits.push(vec![a, b]), // both are unconnected
@@ -99,38 +91,39 @@ fn parse(input: &str) -> Circuits {
Circuits { Circuits {
junctions, junctions,
circuits: Vec::new(), circuits: Vec::new(),
checked: HashSet::new(),
} }
} }
#[aoc(day8, part1)] fn part1_impl(input: &Circuits, n: usize) -> u64 {
fn part1(input: &Circuits) -> u64 {
let mut circuits = input.clone(); let mut circuits = input.clone();
for (a, b, d) in circuits for (a, b, _d) in circuits
.junctions .junctions
.iter() .iter()
.enumerate() .enumerate()
.combinations(2) .combinations(2)
.map(|p| (p[0].0, p[1].0, p[0].1.distance(p[1].1))) .map(|p| (p[0].0, p[1].0, p[0].1.distance(p[1].1)))
.sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) .sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
.take(1000) .take(n)
{ {
println!(
"connecting {} <-> {} = {d}",
circuits.junctions[a], circuits.junctions[b]
);
circuits.connect(a, b) circuits.connect(a, b)
} }
println!("{:?}", circuits.circuits);
circuits circuits
.circuits .circuits
.iter() .iter()
.sorted_by_key(|c| c.len())
.rev()
.take(3) .take(3)
.map(|c| c.len()) .map(|c| c.len())
.reduce(|a, b| a * b) .reduce(|a, b| a * b)
.unwrap() as u64 .unwrap() as u64
} }
#[aoc(day8, part1)]
fn part1(input: &Circuits) -> u64 {
part1_impl(input, 1000)
}
#[aoc(day8, part2)] #[aoc(day8, part2)]
fn part2(input: &Circuits) -> u64 { fn part2(input: &Circuits) -> u64 {
0 0
@@ -163,7 +156,7 @@ mod tests {
#[test] #[test]
fn part1_example() { fn part1_example() {
assert_eq!(part1(&parse(EXAMPLE)), 40); assert_eq!(part1_impl(&parse(EXAMPLE), 10), 40);
} }
#[test] #[test]