-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexercise_8_4_4.rs
More file actions
57 lines (46 loc) · 1.42 KB
/
Copy pathexercise_8_4_4.rs
File metadata and controls
57 lines (46 loc) · 1.42 KB
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
use super::super::extra;
fn magnitude2((x, y): &(f64, f64)) -> f64 {
x * x + y * y
}
#[allow(
clippy::cast_precision_loss,
clippy::cast_sign_loss,
clippy::cast_possible_truncation
)] // Expected.
pub fn bucker_sort_points(a: &mut [(f64, f64)]) {
let n = a.len() as f64;
extra::bucket_sort_by(
a,
|p| (n * magnitude2(p)).ceil() as usize - 1,
|lhs, rhs| magnitude2(lhs).partial_cmp(&magnitude2(rhs)).unwrap(),
);
}
#[cfg(test)]
mod tests {
use crate::test_utilities;
use rand::Rng;
use std::iter;
#[test]
fn test_bucket_sort_points() {
let mut a = Vec::new();
let mut b = Vec::new();
let mut rng = rand::thread_rng();
for n in 0_usize..10 {
for _ in 0..(1 << n) {
test_utilities::assign_vec_from_iter(
&mut a,
iter::repeat_with(|| (rng.gen(), rng.gen()))
.filter(|p| {
let r2 = super::magnitude2(p);
r2 > 0.0 && r2 <= 1.0
})
.take(n),
);
test_utilities::assign_vec(&mut b, &a);
super::bucker_sort_points(&mut b);
a.sort_unstable_by(|lhs, rhs| super::magnitude2(lhs).partial_cmp(&super::magnitude2(rhs)).unwrap());
assert_eq!(a, b);
}
}
}
}