day10 task 1
This commit is contained in:
@@ -21,7 +21,7 @@ fn task1(asteroids: &HashSet<(i32, i32)>) {
|
||||
let max = asteroids
|
||||
.iter()
|
||||
.map(|asteroid| {
|
||||
//println!("inspecting {:?}", asteroid);
|
||||
println!("inspecting {:?}", asteroid);
|
||||
// map to number of other asteroids it sees
|
||||
let mut others = asteroids.clone();
|
||||
others.remove(&asteroid);
|
||||
@@ -29,11 +29,15 @@ fn task1(asteroids: &HashSet<(i32, i32)>) {
|
||||
let count = others
|
||||
.iter()
|
||||
.filter(|target| {
|
||||
!others
|
||||
let blocker = others
|
||||
.iter()
|
||||
.any(|occluder| blocks_view(*asteroid, **target, *occluder))
|
||||
.find(|occluder| blocks_view(*asteroid, **target, **occluder));
|
||||
if let Some(occluder) = blocker {
|
||||
println!("{:?} -> X{:?}X -> {:?}", asteroid, occluder, target);
|
||||
}
|
||||
!blocker.is_some()
|
||||
})
|
||||
//.inspect(|target| println!("sees {:?}", target))
|
||||
.inspect(|target| println!("sees {:?}", target))
|
||||
.count();
|
||||
println!("{:?}: {}", asteroid, count);
|
||||
count
|
||||
@@ -43,29 +47,29 @@ fn task1(asteroids: &HashSet<(i32, i32)>) {
|
||||
println!(
|
||||
"Task 1: maximum visible asteroids from another asteroid are {}",
|
||||
max
|
||||
); //283 too high, 257 too low
|
||||
);
|
||||
}
|
||||
|
||||
fn blocks_view(pov: (i32, i32), target: (i32, i32), occluder: (i32, i32)) -> bool {
|
||||
let ux = occluder.0 - pov.0;
|
||||
let uy = occluder.1 - pov.1;
|
||||
|
||||
let sx = (target.0 - pov.0) as f32 / ux as f32;
|
||||
let sy = (target.1 - pov.1) as f32 / uy as f32;
|
||||
//dbg!((ux, uy, sx, sy));
|
||||
match (ux, uy) {
|
||||
(0, _) => sy.abs() > 1.0 && target.0 == pov.0,
|
||||
(_, 0) => sx.abs() > 1.0 && target.1 == pov.1,
|
||||
(_, _) => sx.abs() > 1.0 && sx == sy,
|
||||
if occluder == target {
|
||||
return false;
|
||||
}
|
||||
fn d(a: (i32, i32), b: (i32, i32)) -> f32 {
|
||||
((a.0 - b.0) as f32).powi(2) + ((a.1 - b.1) as f32).powi(2).sqrt()
|
||||
}
|
||||
// using polar coordinates
|
||||
let alpha_occluder = ((occluder.1 - pov.1) as f32).atan2((occluder.0 - pov.0) as f32);
|
||||
let alpha_target = ((target.1 - pov.1) as f32).atan2((target.0 - pov.0) as f32);
|
||||
(alpha_occluder - alpha_target).abs() <= std::f32::EPSILON && d(pov, target) > d(pov, occluder)
|
||||
}
|
||||
|
||||
mod test {
|
||||
#[test]
|
||||
fn block_test() {
|
||||
assert_eq!(true, super::blocks_view((3, 4), (1, 0), (2, 2)));
|
||||
assert_ne!(true, super::blocks_view((3, 4), (2, 2), (1, 0)));
|
||||
assert_ne!(true, super::blocks_view((3, 4), (1, 0), (1, 2)));
|
||||
assert_eq!(false, super::blocks_view((3, 4), (2, 2), (1, 0)));
|
||||
assert_eq!(false, super::blocks_view((3, 4), (1, 0), (1, 2)));
|
||||
assert_eq!(true, super::blocks_view((4, 4), (4, 0), (4, 3)));
|
||||
assert_eq!(false, super::blocks_view((3, 2), (1, 0), (4, 3)));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user