problems(rs): add “1502. Can Make Arithmetic Progression From Sequence”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
2d63ead6b8
commit
2bf902b161
1 changed files with 31 additions and 0 deletions
31
problems/rs/can-make-arithmetic-progression-from-sequence.rs
Normal file
31
problems/rs/can-make-arithmetic-progression-from-sequence.rs
Normal 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]));
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue