c1: first working impl

This commit is contained in:
raf 2024-12-01 11:37:44 +03:00
parent c0343c15ae
commit 85a7ee0b8e
Signed by: NotAShelf
GPG key ID: AF26552424E53993

View file

@ -1,3 +1,58 @@
fn main() {
println!("Hello, world!");
use std::io;
fn triangle_area(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) -> f64 {
((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0).abs()
}
// We use the barycentric coordinate method to decide whether
// given point lies within the triangle. It took me more than
// I would like to admit to remember that name.
fn main() {
let mut input = String::new();
println!("Enter the coordinates for the triangle's vertices (x1 y1 x2 y2 x3 y3):");
io::stdin().read_line(&mut input).unwrap();
let coords: Vec<f64> = input
.trim()
.split_whitespace()
.filter_map(|x| x.parse::<f64>().ok())
.collect();
if coords.len() != 6 {
println!("Invalid input: expected 6 numbers for the triangle's vertices.");
return;
}
let (x1, y1, x2, y2, x3, y3) = (
coords[0], coords[1], coords[2], coords[3], coords[4], coords[5],
);
input.clear();
println!("Enter the coordinates for the point to test (px py):");
io::stdin().read_line(&mut input).unwrap(); // I'm getting executed for this unwrap
let point: Vec<f64> = input
.trim()
.split_whitespace()
.filter_map(|x| x.parse::<f64>().ok())
.collect();
if point.len() != 2 {
println!("Invalid input: expected 2 numbers for the point's coordinates.");
return;
}
let (px, py) = (point[0], point[1]);
// calculate areas
let total_area = triangle_area(x1, y1, x2, y2, x3, y3);
let area1 = triangle_area(px, py, x2, y2, x3, y3);
let area2 = triangle_area(x1, y1, px, py, x3, y3);
let area3 = triangle_area(x1, y1, x2, y2, px, py);
// check if the sum of the smaller areas matches the total area
if (area1 + area2 + area3 - total_area).abs() < 1e-9 {
println!("The point ({}, {}) lies inside the triangle.", px, py);
} else {
println!("The point ({}, {}) lies outside the triangle.", px, py);
}
}