day8: avoid floats for performance
This commit is contained in:
25
src/day8.rs
25
src/day8.rs
@@ -1,25 +1,26 @@
|
|||||||
use std::{f64, fmt::Display};
|
use std::fmt::Display;
|
||||||
|
|
||||||
use aoc_runner_derive::{aoc, aoc_generator};
|
use aoc_runner_derive::{aoc, aoc_generator};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
|
|
||||||
#[derive(PartialEq, Clone, Debug)]
|
#[derive(PartialEq, Clone, Debug)]
|
||||||
struct Junction {
|
struct Junction {
|
||||||
pos: (f64, f64, f64),
|
pos: (i64, i64, i64),
|
||||||
}
|
}
|
||||||
|
|
||||||
fn distance(a: &Junction, b: &Junction) -> f64 {
|
fn squared_distance(a: &Junction, b: &Junction) -> u64 {
|
||||||
if a.pos == b.pos {
|
if a.pos == b.pos {
|
||||||
0f64
|
0
|
||||||
} else {
|
} else {
|
||||||
((a.pos.0 - b.pos.0).powi(2) + (a.pos.1 - b.pos.1).powi(2) + (a.pos.2 - b.pos.2).powi(2))
|
(a.pos.0 - b.pos.0).pow(2) as u64
|
||||||
.sqrt()
|
+ (a.pos.1 - b.pos.1).pow(2) as u64
|
||||||
|
+ (a.pos.2 - b.pos.2).pow(2) as u64
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Junction {
|
impl Junction {
|
||||||
fn distance(&self, other: &Junction) -> f64 {
|
fn squared_distance(&self, other: &Junction) -> u64 {
|
||||||
distance(self, other)
|
squared_distance(self, other)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,8 +94,8 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 {
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.tuple_combinations()
|
.tuple_combinations()
|
||||||
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b)))
|
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.squared_distance(b)))
|
||||||
.sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
|
.sorted_unstable_by_key(|(_a_pos, _b_pos, d)| *d)
|
||||||
.take(n)
|
.take(n)
|
||||||
{
|
{
|
||||||
circuits.connect(a, b)
|
circuits.connect(a, b)
|
||||||
@@ -125,8 +126,8 @@ fn part2(input: &Circuits) -> u64 {
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.tuple_combinations()
|
.tuple_combinations()
|
||||||
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b)))
|
.map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.squared_distance(b)))
|
||||||
.sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap())
|
.sorted_unstable_by_key(|(_a_pos, _b_pos, d)| *d)
|
||||||
{
|
{
|
||||||
circuits.connect(a, b);
|
circuits.connect(a, b);
|
||||||
if circuits.circuits.len() == 1 {
|
if circuits.circuits.len() == 1 {
|
||||||
|
|||||||
Reference in New Issue
Block a user