day8: we don't need stable sort and unstable is faster

This commit is contained in:
2025-12-08 02:55:04 -08:00
parent 09ca512fcc
commit db214ca958
2 changed files with 12 additions and 12 deletions

2
.cargo/config.toml Normal file
View File

@@ -0,0 +1,2 @@
[build]
rustflags = ["-C", "target-cpu=native"]

View File

@@ -3,17 +3,16 @@ use std::{f64, fmt::Display};
use aoc_runner_derive::{aoc, aoc_generator};
use itertools::Itertools;
#[derive(Eq, PartialEq, Clone, Debug, Hash)]
#[derive(PartialEq, Clone, Debug)]
struct Junction {
pos: (i64, i64, i64),
pos: (f64, f64, f64),
}
fn distance(a: &Junction, b: &Junction) -> f64 {
if a.pos == b.pos {
0f64
} else {
(((a.pos.0 - b.pos.0).pow(2) + (a.pos.1 - b.pos.1).pow(2) + (a.pos.2 - b.pos.2).pow(2))
as f64)
((a.pos.0 - b.pos.0).powi(2) + (a.pos.1 - b.pos.1).powi(2) + (a.pos.2 - b.pos.2).powi(2))
.sqrt()
}
}
@@ -64,8 +63,7 @@ impl Circuits {
if a == b {
return;
}
let mut items = Vec::new();
std::mem::swap(&mut items, &mut self.circuits[b]);
let mut items = std::mem::take(&mut self.circuits[b]);
self.circuits[a].append(&mut items);
self.circuits.remove(b);
}
@@ -96,7 +94,7 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 {
.enumerate()
.tuple_combinations()
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b)))
.sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
.sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
.take(n)
{
circuits.connect(a, b)
@@ -105,10 +103,10 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 {
circuits
.circuits
.iter()
.sorted_by_key(|c| c.len())
.map(|c| c.len())
.sorted_unstable()
.rev()
.take(3)
.map(|c| c.len())
.reduce(|a, b| a * b)
.unwrap() as u64
}
@@ -126,9 +124,9 @@ fn part2(input: &Circuits) -> u64 {
.junctions
.iter()
.enumerate()
.combinations(2)
.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())
.tuple_combinations()
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b)))
.sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
{
circuits.connect(a, b);
if circuits.circuits.len() == 1 {