-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12.rs
122 lines (102 loc) · 2.48 KB
/
day12.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::{cmp::Ordering, error::Error, ops::Deref};
// 1. Update the function signature to accept and return references to Locations
pub fn find_most_dense_location(locations: &[Location]) -> Result<&Location, Box<dyn Error>> {
locations
.into_iter()
.max_by(|a, b| {
a.density()
.partial_cmp(&b.density())
.unwrap_or(Ordering::Equal)
})
.ok_or("No locations found".into())
}
pub fn find_nearest_location(locations: &[Location]) -> Result<&Location, Box<dyn Error>> {
locations
.iter()
.filter(|location| location.density() >= 1000.0)
.min_by(|a, b| {
a.x.hypot(a.y)
.partial_cmp(&b.x.hypot(b.y))
.unwrap_or(Ordering::Equal)
})
.ok_or("No locations found".into())
}
const SNOWBALL_WEIGHT_KG: f64 = 0.2;
const SNOWBALL_WEIGHT_LB: f64 = 0.441;
#[derive(Debug)]
pub struct SnowKg(pub f64);
impl SnowKg {
pub fn new(kg: f64) -> Self {
SnowKg(kg)
}
}
impl Deref for SnowKg {
type Target = f64;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug)]
pub struct SnowLb(pub f64);
impl SnowLb {
pub fn new(lb: f64) -> Self {
SnowLb(lb)
}
}
impl Deref for SnowLb {
type Target = f64;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Snowball(pub i64);
impl Snowball {
pub fn new(snowballs: i64) -> Self {
Snowball(snowballs)
}
}
impl Deref for Snowball {
type Target = i64;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<SnowKg> for Snowball {
fn from(kg: SnowKg) -> Self {
let snowballs = (*kg / SNOWBALL_WEIGHT_KG).round() as i64;
Snowball(snowballs)
}
}
impl From<SnowLb> for Snowball {
fn from(lb: SnowLb) -> Self {
let snowballs = (*lb / SNOWBALL_WEIGHT_LB).round() as i64;
Snowball(snowballs)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Location {
pub x: f64,
pub y: f64,
pub z: f64,
pub area: f64,
pub snow: Snowball,
}
impl Location {
pub fn new(x: f64, y: f64, z: f64, area: f64, snow: impl Into<Snowball>) -> Self {
Self {
x,
y,
z,
area,
snow: snow.into(),
}
}
pub fn density(&self) -> f64 {
if self.area > 0.0 {
*self.snow as f64 / self.area
} else {
0.0
}
}
}