1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/problems/rs/check-if-it-is-a-straight-line.rs
2023-06-05 23:28:17 +02:00

58 lines
1.3 KiB
Rust

struct Solution {}
impl Solution {
fn x_diff(a: &[i32], b: &[i32]) -> i32 {
a[0] - b[0]
}
fn y_diff(a: &[i32], b: &[i32]) -> i32 {
a[1] - b[1]
}
pub fn check_straight_line(coordinates: Vec<Vec<i32>>) -> bool {
assert!(coordinates.len() > 1);
let (dx, dy) = (
Solution::x_diff(&coordinates[0], &coordinates[1]),
Solution::y_diff(&coordinates[0], &coordinates[1]),
);
coordinates.iter().all(|pt| {
dx * Solution::y_diff(pt, &coordinates[0]) == dy * Solution::x_diff(pt, &coordinates[0])
})
}
}
fn main() {}
#[cfg(test)]
mod tests {
use super::*;
// Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
// Output: true
#[test]
fn example_1() {
assert!(Solution::check_straight_line(vec![
vec![1, 2],
vec![2, 3],
vec![3, 4],
vec![4, 5],
vec![5, 6],
vec![6, 7]
]));
}
// Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
// Output: false
#[test]
fn example_2() {
assert!(!Solution::check_straight_line(vec![
vec![1, 1],
vec![2, 2],
vec![3, 4],
vec![4, 5],
vec![5, 6],
vec![7, 7]
]));
}
}