1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 09:59:41 +01:00
LeetCode/problems/rs/can-make-arithmetic-progression-from-sequence.rs
2023-06-06 10:42:37 +02:00

31 lines
907 B
Rust

struct Solution {}
impl Solution {
pub fn can_make_arithmetic_progression(mut arr: Vec<i32>) -> bool {
arr.sort();
let diffs: Vec<i32> = arr.windows(2).map(|pair| pair[1] - pair[0]).collect();
diffs.windows(2).all(|pair| pair[0] == pair[1])
}
}
fn main() {}
#[cfg(test)]
mod tests {
use super::*;
// Input: arr = [3,5,1]
// Output: true
// Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
#[test]
fn example_1() {
assert!(Solution::can_make_arithmetic_progression(vec![3, 5, 1]));
}
// Input: arr = [1,2,4]
// Output: false
// Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
#[test]
fn example_2() {
assert!(!Solution::can_make_arithmetic_progression(vec![2, 4, 1]));
}
}