problems(rs): add “1502. Can Make Arithmetic Progression From Sequence”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-06-06 10:42:37 +02:00
parent 2d63ead6b8
commit 2bf902b161
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,31 @@
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]));
}
}