mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(rs): add “1232. Check If It Is a Straight Line”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
35252ff989
commit
2d63ead6b8
1 changed files with 58 additions and 0 deletions
58
problems/rs/check-if-it-is-a-straight-line.rs
Normal file
58
problems/rs/check-if-it-is-a-straight-line.rs
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
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]
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue