init
This commit is contained in:
91
problems/p102/src/main.rs
Normal file
91
problems/p102/src/main.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
use rayon::prelude::*;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader},
|
||||
};
|
||||
|
||||
struct Point {
|
||||
x: i32,
|
||||
y: i32,
|
||||
}
|
||||
|
||||
impl Point {
|
||||
fn cross_product(&self, b: &Point, c: &Point) -> i32 {
|
||||
(b.x - self.x) * (c.y - self.y) - (b.y - self.y) * (c.x - self.x)
|
||||
}
|
||||
}
|
||||
|
||||
struct Triangle {
|
||||
a: Point,
|
||||
b: Point,
|
||||
c: Point,
|
||||
}
|
||||
|
||||
fn load_triangle() -> Vec<Triangle> {
|
||||
let mut tris = Vec::new();
|
||||
let file = File::open("./problems/p102/p102_triangles.txt").unwrap();
|
||||
let reader = BufReader::new(file);
|
||||
|
||||
let lines: Vec<String> = reader.lines().map(|s| s.unwrap()).collect();
|
||||
for line in lines {
|
||||
// "-340,495,-153,-910,835,-947",
|
||||
let values: Vec<&str> = line.split(',').collect();
|
||||
let values: Vec<i32> = values.iter().map(|&x| x.parse::<i32>().unwrap()).collect();
|
||||
|
||||
let triangle = Triangle {
|
||||
a: Point {
|
||||
x: values[0],
|
||||
y: values[1],
|
||||
},
|
||||
b: Point {
|
||||
x: values[2],
|
||||
y: values[3],
|
||||
},
|
||||
c: Point {
|
||||
x: values[4],
|
||||
y: values[5],
|
||||
},
|
||||
};
|
||||
tris.push(triangle);
|
||||
}
|
||||
|
||||
tris
|
||||
}
|
||||
|
||||
fn is_include_origin(tri: &Triangle) -> bool {
|
||||
let a = &tri.a;
|
||||
let b = &tri.b;
|
||||
let c = &tri.c;
|
||||
let origin = Point { x: 0, y: 0 };
|
||||
// 对于两个向量 u = (u.x, u.y) 和 v = (v.x, v.y):
|
||||
// 叉积 = u.x * v.y - u.y * v.x
|
||||
|
||||
let ab_ao = a.cross_product(b, &origin);
|
||||
let bc_bo = b.cross_product(c, &origin);
|
||||
let ca_co = c.cross_product(a, &origin);
|
||||
if ab_ao == 0 || bc_bo == 0 || ca_co == 0 {
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
(ab_ao > 0, bc_bo > 0, ca_co > 0),
|
||||
(true, true, true) | (false, false, false)
|
||||
)
|
||||
}
|
||||
#[test]
|
||||
fn test_is_include_origin() {
|
||||
let a = Triangle {
|
||||
a: Point { x: -340, y: 495 },
|
||||
b: Point { x: -153, y: -910 },
|
||||
c: Point { x: 835, y: -947 },
|
||||
};
|
||||
assert!(is_include_origin(&a));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let tris = load_triangle();
|
||||
let count = tris
|
||||
.par_iter()
|
||||
.filter(|&tri| is_include_origin(tri))
|
||||
.count();
|
||||
println!("{count}");
|
||||
}
|
||||
Reference in New Issue
Block a user